-- Create agent_settings table for storing AI agent configurations
CREATE TABLE public.agent_settings (
  id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY,
  agent_type TEXT NOT NULL UNIQUE, -- 'manager', 'product', 'marketing', 'service', 'finance'
  
  -- Response style settings
  response_style TEXT NOT NULL DEFAULT 'balanced', -- 'concise', 'balanced', 'detailed'
  tone TEXT NOT NULL DEFAULT 'professional', -- 'professional', 'friendly', 'formal'
  
  -- Decision authority settings
  auto_execute_enabled BOOLEAN NOT NULL DEFAULT false,
  max_auto_amount NUMERIC NOT NULL DEFAULT 0, -- Maximum amount for auto-execution
  requires_approval_types TEXT[] NOT NULL DEFAULT ARRAY[]::TEXT[], -- Action types requiring approval
  
  -- Notification preferences
  notify_on_insights BOOLEAN NOT NULL DEFAULT true,
  notify_on_approvals BOOLEAN NOT NULL DEFAULT true,
  notify_on_errors BOOLEAN NOT NULL DEFAULT true,
  
  -- Goal settings (JSONB for flexibility)
  monthly_goals JSONB NOT NULL DEFAULT '{}'::JSONB,
  
  -- Status
  is_active BOOLEAN NOT NULL DEFAULT true,
  
  -- Timestamps
  created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
  updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now()
);

-- Enable RLS
ALTER TABLE public.agent_settings ENABLE ROW LEVEL SECURITY;

-- Admins can manage agent settings
CREATE POLICY "Admins can manage agent settings"
  ON public.agent_settings
  FOR ALL
  USING (EXISTS (
    SELECT 1 FROM profiles
    WHERE profiles.user_id = auth.uid() AND profiles.role = 'admin'
  ));

-- Anyone can view agent settings (for display purposes)
CREATE POLICY "Anyone can view agent settings"
  ON public.agent_settings
  FOR SELECT
  USING (true);

-- Insert default settings for all agents
INSERT INTO public.agent_settings (agent_type, response_style, tone, monthly_goals) VALUES
  ('manager', 'balanced', 'professional', '{"gmv_target": 100000, "growth_rate": 0.2}'::JSONB),
  ('product', 'detailed', 'professional', '{"new_products": 10, "stock_optimization": 0.95}'::JSONB),
  ('marketing', 'balanced', 'friendly', '{"campaign_count": 5, "conversion_rate": 0.15}'::JSONB),
  ('service', 'detailed', 'friendly', '{"response_time_hours": 24, "satisfaction_rate": 0.95}'::JSONB),
  ('finance', 'concise', 'formal', '{"collection_rate": 0.98, "settlement_days": 3}'::JSONB);

-- Create index for faster lookups
CREATE INDEX idx_agent_settings_type ON public.agent_settings(agent_type);

-- Create trigger for updated_at
CREATE TRIGGER update_agent_settings_updated_at
  BEFORE UPDATE ON public.agent_settings
  FOR EACH ROW
  EXECUTE FUNCTION public.update_updated_at_column();