import {
  cmsPages,
  cmsContentBlocks,
  cmsFeatures,
  cmsStats,
  cmsTestimonials,
  type CmsPage,
  type InsertCmsPage,
  type CmsContentBlock,
  type InsertCmsContentBlock,
  type CmsFeature,
  type InsertCmsFeature,
  type CmsStat,
  type InsertCmsStat,
  type CmsTestimonial,
  type InsertCmsTestimonial,
} from "@shared/schema";
import { db } from "./db";
import { eq, desc, asc } from "drizzle-orm";

export class CmsStorage {
  // Pages
  async getCmsPages(): Promise<CmsPage[]> {
    return await db.select().from(cmsPages).orderBy(asc(cmsPages.createdAt));
  }

  async getCmsPage(id: number): Promise<CmsPage | undefined> {
    const [page] = await db.select().from(cmsPages).where(eq(cmsPages.id, id));
    return page;
  }

  async getCmsPageBySlug(slug: string): Promise<CmsPage | undefined> {
    const [page] = await db.select().from(cmsPages).where(eq(cmsPages.slug, slug));
    return page;
  }

  async createCmsPage(page: InsertCmsPage): Promise<CmsPage> {
    const [newPage] = await db.insert(cmsPages).values(page).returning();
    return newPage;
  }

  async updateCmsPage(id: number, page: Partial<InsertCmsPage>): Promise<CmsPage> {
    const [updatedPage] = await db
      .update(cmsPages)
      .set({ ...page, updatedAt: new Date() })
      .where(eq(cmsPages.id, id))
      .returning();
    return updatedPage;
  }

  async deleteCmsPage(id: number): Promise<void> {
    await db.delete(cmsPages).where(eq(cmsPages.id, id));
  }

  // Content Blocks
  async getCmsContentBlocks(pageId: number): Promise<CmsContentBlock[]> {
    return await db
      .select()
      .from(cmsContentBlocks)
      .where(eq(cmsContentBlocks.pageId, pageId))
      .orderBy(asc(cmsContentBlocks.sortOrder));
  }

  async getCmsContentBlock(id: number): Promise<CmsContentBlock | undefined> {
    const [block] = await db.select().from(cmsContentBlocks).where(eq(cmsContentBlocks.id, id));
    return block;
  }

  async createCmsContentBlock(block: InsertCmsContentBlock): Promise<CmsContentBlock> {
    const [newBlock] = await db.insert(cmsContentBlocks).values(block).returning();
    return newBlock;
  }

  async updateCmsContentBlock(id: number, block: Partial<InsertCmsContentBlock>): Promise<CmsContentBlock> {
    const [updatedBlock] = await db
      .update(cmsContentBlocks)
      .set({ ...block, updatedAt: new Date() })
      .where(eq(cmsContentBlocks.id, id))
      .returning();
    return updatedBlock;
  }

  async deleteCmsContentBlock(id: number): Promise<void> {
    await db.delete(cmsContentBlocks).where(eq(cmsContentBlocks.id, id));
  }

  // Features
  async getCmsFeatures(): Promise<CmsFeature[]> {
    return await db
      .select()
      .from(cmsFeatures)
      .where(eq(cmsFeatures.isActive, true))
      .orderBy(asc(cmsFeatures.sortOrder));
  }

  async getCmsFeature(id: number): Promise<CmsFeature | undefined> {
    const [feature] = await db.select().from(cmsFeatures).where(eq(cmsFeatures.id, id));
    return feature;
  }

  async createCmsFeature(feature: InsertCmsFeature): Promise<CmsFeature> {
    const [newFeature] = await db.insert(cmsFeatures).values(feature).returning();
    return newFeature;
  }

  async updateCmsFeature(id: number, feature: Partial<InsertCmsFeature>): Promise<CmsFeature> {
    const [updatedFeature] = await db
      .update(cmsFeatures)
      .set({ ...feature, updatedAt: new Date() })
      .where(eq(cmsFeatures.id, id))
      .returning();
    return updatedFeature;
  }

  async deleteCmsFeature(id: number): Promise<void> {
    await db.delete(cmsFeatures).where(eq(cmsFeatures.id, id));
  }

  // Stats
  async getCmsStats(): Promise<CmsStat[]> {
    return await db
      .select()
      .from(cmsStats)
      .where(eq(cmsStats.isActive, true))
      .orderBy(asc(cmsStats.sortOrder));
  }

  async getCmsStat(id: number): Promise<CmsStat | undefined> {
    const [stat] = await db.select().from(cmsStats).where(eq(cmsStats.id, id));
    return stat;
  }

  async createCmsStat(stat: InsertCmsStat): Promise<CmsStat> {
    const [newStat] = await db.insert(cmsStats).values(stat).returning();
    return newStat;
  }

  async updateCmsStat(id: number, stat: Partial<InsertCmsStat>): Promise<CmsStat> {
    const [updatedStat] = await db
      .update(cmsStats)
      .set({ ...stat, updatedAt: new Date() })
      .where(eq(cmsStats.id, id))
      .returning();
    return updatedStat;
  }

  async deleteCmsStat(id: number): Promise<void> {
    await db.delete(cmsStats).where(eq(cmsStats.id, id));
  }

  // Testimonials
  async getCmsTestimonials(): Promise<CmsTestimonial[]> {
    return await db
      .select()
      .from(cmsTestimonials)
      .where(eq(cmsTestimonials.isActive, true))
      .orderBy(asc(cmsTestimonials.sortOrder));
  }

  async getCmsTestimonial(id: number): Promise<CmsTestimonial | undefined> {
    const [testimonial] = await db.select().from(cmsTestimonials).where(eq(cmsTestimonials.id, id));
    return testimonial;
  }

  async createCmsTestimonial(testimonial: InsertCmsTestimonial): Promise<CmsTestimonial> {
    const [newTestimonial] = await db.insert(cmsTestimonials).values(testimonial).returning();
    return newTestimonial;
  }

  async updateCmsTestimonial(id: number, testimonial: Partial<InsertCmsTestimonial>): Promise<CmsTestimonial> {
    const [updatedTestimonial] = await db
      .update(cmsTestimonials)
      .set({ ...testimonial, updatedAt: new Date() })
      .where(eq(cmsTestimonials.id, id))
      .returning();
    return updatedTestimonial;
  }

  async deleteCmsTestimonial(id: number): Promise<void> {
    await db.delete(cmsTestimonials).where(eq(cmsTestimonials.id, id));
  }

  // Initialize default content
  async initializeDefaultContent(): Promise<void> {
    // Check if landing page already exists
    const landingPage = await this.getCmsPageBySlug('landing');
    if (landingPage) return;

    // Create landing page
    const page = await this.createCmsPage({
      slug: 'landing',
      title: 'SportsPro Landing Page',
      metaDescription: 'Professional sports management platform with AI-powered features',
      status: 'published'
    });

    // Create hero content block
    await this.createCmsContentBlock({
      pageId: page.id,
      blockKey: 'hero',
      blockType: 'hero',
      title: 'Professional Sports Management',
      subtitle: 'Transform your sports organization with AI-powered analytics, automated video highlights, and comprehensive team management tools trusted by professional clubs worldwide.',
      buttonText: 'Start Free Trial',
      buttonUrl: '/auth',
      sortOrder: 1,
      metadata: {
        badge: 'New: AI-Powered Video Highlights'
      }
    });

    // Create default features
    const defaultFeatures = [
      {
        icon: 'Video',
        title: 'AI Video Highlights',
        description: 'Automatically detect and compile highlight reels from game footage with advanced AI analysis.',
        features: ['Auto highlight detection', 'Multiple export formats', 'Custom transitions'],
        color: 'from-purple-500 to-pink-500',
        sortOrder: 1
      },
      {
        icon: 'Brain',
        title: 'Smart Onboarding',
        description: 'Get personalized setup recommendations based on your sport, team size, and objectives.',
        features: ['Sport-specific guidance', 'Setup scoring', 'Progress tracking'],
        color: 'from-blue-500 to-cyan-500',
        sortOrder: 2
      },
      {
        icon: 'Fingerprint',
        title: 'Biometric Security',
        description: 'Advanced facial recognition and comprehensive privacy controls for player data.',
        features: ['Facial recognition', 'Privacy presets', 'Secure data handling'],
        color: 'from-green-500 to-emerald-500',
        sortOrder: 3
      },
      {
        icon: 'Users',
        title: 'Team Management',
        description: 'Complete player roster management with advanced search, filtering, and bulk operations.',
        features: ['Player profiles', 'Team organization', 'Bulk actions'],
        color: 'from-orange-500 to-red-500',
        sortOrder: 4
      }
    ];

    for (const feature of defaultFeatures) {
      await this.createCmsFeature(feature);
    }

    // Create default stats
    const defaultStats = [
      {
        icon: 'Users',
        statValue: '10,000+',
        label: 'Active Teams',
        sortOrder: 1
      },
      {
        icon: 'UserPlus',
        statValue: '500K+',
        label: 'Players Managed',
        sortOrder: 2
      },
      {
        icon: 'Globe',
        statValue: '50+',
        label: 'Countries',
        sortOrder: 3
      },
      {
        icon: 'CheckCircle',
        statValue: '99.9%',
        label: 'Uptime',
        sortOrder: 4
      }
    ];

    for (const stat of defaultStats) {
      await this.createCmsStat(stat);
    }
  }
}

export const cmsStorage = new CmsStorage();