-- Marketing Kit support for Event Marketing Toolkit
-- This migration adds tables to store marketing kit assets and templates

-- Table to store marketing kit assets for each event
CREATE TABLE IF NOT EXISTS marketing_kit_assets (
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  event_id UUID NOT NULL REFERENCES events(id) ON DELETE CASCADE,
  organization_id UUID NOT NULL REFERENCES organizations(id) ON DELETE CASCADE,
  asset_type TEXT NOT NULL CHECK (asset_type IN ('social_post', 'flyer', 'email_template', 'qr_code')),
  platform TEXT, -- For social posts: 'facebook', 'instagram', 'twitter', 'linkedin'
  title TEXT NOT NULL,
  content TEXT, -- JSON content for templates/configs
  image_url TEXT, -- Generated image URL
  download_url TEXT, -- Direct download URL for assets
  file_format TEXT, -- 'png', 'jpg', 'html', 'txt', etc.
  dimensions JSON, -- {"width": 1080, "height": 1080} for images
  generated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
  expires_at TIMESTAMP WITH TIME ZONE, -- For temporary download links
  metadata JSON, -- Additional configuration/settings
  is_active BOOLEAN DEFAULT true,
  created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
  updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- Table to store reusable marketing templates
CREATE TABLE IF NOT EXISTS marketing_templates (
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  organization_id UUID REFERENCES organizations(id) ON DELETE CASCADE,
  template_type TEXT NOT NULL CHECK (template_type IN ('social_post', 'flyer', 'email_template')),
  platform TEXT, -- For social posts: 'facebook', 'instagram', 'twitter', 'linkedin'
  name TEXT NOT NULL,
  description TEXT,
  template_data JSON NOT NULL, -- Template configuration and layout
  preview_image_url TEXT,
  is_default BOOLEAN DEFAULT false,
  is_active BOOLEAN DEFAULT true,
  created_by UUID REFERENCES users(id),
  created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
  updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- Table to track marketing kit generations and downloads
CREATE TABLE IF NOT EXISTS marketing_kit_generations (
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  event_id UUID NOT NULL REFERENCES events(id) ON DELETE CASCADE,
  organization_id UUID NOT NULL REFERENCES organizations(id) ON DELETE CASCADE,
  generated_by UUID REFERENCES users(id),
  generation_type TEXT NOT NULL CHECK (generation_type IN ('full_kit', 'individual_asset')),
  assets_included TEXT[], -- Array of asset types included
  zip_file_url TEXT, -- URL to download complete kit
  zip_expires_at TIMESTAMP WITH TIME ZONE,
  generation_status TEXT DEFAULT 'pending' CHECK (generation_status IN ('pending', 'processing', 'completed', 'failed')),
  error_message TEXT,
  download_count INTEGER DEFAULT 0,
  last_downloaded_at TIMESTAMP WITH TIME ZONE,
  created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
  updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- Indexes for performance
CREATE INDEX IF NOT EXISTS idx_marketing_kit_assets_event_id ON marketing_kit_assets(event_id);
CREATE INDEX IF NOT EXISTS idx_marketing_kit_assets_org_id ON marketing_kit_assets(organization_id);
CREATE INDEX IF NOT EXISTS idx_marketing_kit_assets_type ON marketing_kit_assets(asset_type);
CREATE INDEX IF NOT EXISTS idx_marketing_templates_org_id ON marketing_templates(organization_id);
CREATE INDEX IF NOT EXISTS idx_marketing_templates_type ON marketing_templates(template_type);
CREATE INDEX IF NOT EXISTS idx_marketing_kit_generations_event_id ON marketing_kit_generations(event_id);
CREATE INDEX IF NOT EXISTS idx_marketing_kit_generations_org_id ON marketing_kit_generations(organization_id);

-- RLS Policies for multi-tenant security
ALTER TABLE marketing_kit_assets ENABLE ROW LEVEL SECURITY;
ALTER TABLE marketing_templates ENABLE ROW LEVEL SECURITY;
ALTER TABLE marketing_kit_generations ENABLE ROW LEVEL SECURITY;

-- Policies for marketing_kit_assets
CREATE POLICY "Users can view marketing kit assets from their organization" ON marketing_kit_assets
  FOR SELECT USING (
    organization_id IN (
      SELECT organization_id FROM users WHERE id = auth.uid()
    )
  );

CREATE POLICY "Users can create marketing kit assets for their organization" ON marketing_kit_assets
  FOR INSERT WITH CHECK (
    organization_id IN (
      SELECT organization_id FROM users WHERE id = auth.uid()
    )
  );

CREATE POLICY "Users can update marketing kit assets from their organization" ON marketing_kit_assets
  FOR UPDATE USING (
    organization_id IN (
      SELECT organization_id FROM users WHERE id = auth.uid()
    )
  );

CREATE POLICY "Users can delete marketing kit assets from their organization" ON marketing_kit_assets
  FOR DELETE USING (
    organization_id IN (
      SELECT organization_id FROM users WHERE id = auth.uid()
    )
  );

-- Policies for marketing_templates
CREATE POLICY "Users can view marketing templates from their organization or default templates" ON marketing_templates
  FOR SELECT USING (
    organization_id IN (
      SELECT organization_id FROM users WHERE id = auth.uid()
    )
    OR organization_id IS NULL -- Global default templates
  );

CREATE POLICY "Users can create marketing templates for their organization" ON marketing_templates
  FOR INSERT WITH CHECK (
    organization_id IN (
      SELECT organization_id FROM users WHERE id = auth.uid()
    )
  );

CREATE POLICY "Users can update marketing templates from their organization" ON marketing_templates
  FOR UPDATE USING (
    organization_id IN (
      SELECT organization_id FROM users WHERE id = auth.uid()
    )
  );

CREATE POLICY "Users can delete marketing templates from their organization" ON marketing_templates
  FOR DELETE USING (
    organization_id IN (
      SELECT organization_id FROM users WHERE id = auth.uid()
    )
  );

-- Policies for marketing_kit_generations
CREATE POLICY "Users can view marketing kit generations from their organization" ON marketing_kit_generations
  FOR SELECT USING (
    organization_id IN (
      SELECT organization_id FROM users WHERE id = auth.uid()
    )
  );

CREATE POLICY "Users can create marketing kit generations for their organization" ON marketing_kit_generations
  FOR INSERT WITH CHECK (
    organization_id IN (
      SELECT organization_id FROM users WHERE id = auth.uid()
    )
  );

CREATE POLICY "Users can update marketing kit generations from their organization" ON marketing_kit_generations
  FOR UPDATE USING (
    organization_id IN (
      SELECT organization_id FROM users WHERE id = auth.uid()
    )
  );

-- Admin bypass policies
CREATE POLICY "Admins can manage all marketing kit assets" ON marketing_kit_assets
  FOR ALL USING (is_admin(auth.uid()));

CREATE POLICY "Admins can manage all marketing templates" ON marketing_templates
  FOR ALL USING (is_admin(auth.uid()));

CREATE POLICY "Admins can manage all marketing kit generations" ON marketing_kit_generations
  FOR ALL USING (is_admin(auth.uid()));

-- Insert some default templates
INSERT INTO marketing_templates (name, description, template_type, platform, template_data, is_default, organization_id) VALUES
-- Facebook Post Template
('Default Facebook Post', 'Standard Facebook event promotion post', 'social_post', 'facebook', 
 '{"background": "gradient-blue", "textColor": "#FFFFFF", "layout": "center", "includeQR": true, "dimensions": {"width": 1200, "height": 630}}', 
 true, NULL),

-- Instagram Post Template  
('Default Instagram Post', 'Square Instagram event promotion post', 'social_post', 'instagram',
 '{"background": "gradient-purple", "textColor": "#FFFFFF", "layout": "center", "includeQR": true, "dimensions": {"width": 1080, "height": 1080}}',
 true, NULL),

-- Twitter Post Template
('Default Twitter Post', 'Twitter event promotion post', 'social_post', 'twitter',
 '{"background": "gradient-blue", "textColor": "#FFFFFF", "layout": "left", "includeQR": true, "dimensions": {"width": 1200, "height": 675}}',
 true, NULL),

-- Email Template
('Default Email Template', 'Standard event promotion email template', 'email_template', NULL,
 '{"subject": "You''re Invited: {EVENT_TITLE}", "headerImage": true, "includeQR": true, "ctaText": "Get Your Tickets", "layout": "centered"}',
 true, NULL),

-- Flyer Template
('Default Event Flyer', 'Standard event flyer design', 'flyer', NULL,
 '{"background": "gradient-blue", "textColor": "#FFFFFF", "layout": "poster", "includeQR": true, "dimensions": {"width": 1080, "height": 1350}}',
 true, NULL);

-- Trigger to update updated_at timestamp
CREATE OR REPLACE FUNCTION update_updated_at_column()
RETURNS TRIGGER AS $$
BEGIN
  NEW.updated_at = NOW();
  RETURN NEW;
END;
$$ language 'plpgsql';

CREATE TRIGGER update_marketing_kit_assets_updated_at BEFORE UPDATE ON marketing_kit_assets FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();
CREATE TRIGGER update_marketing_templates_updated_at BEFORE UPDATE ON marketing_templates FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();
CREATE TRIGGER update_marketing_kit_generations_updated_at BEFORE UPDATE ON marketing_kit_generations FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();