import { NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { customPages, navigationItems, homepageContent } from '@/shared/schema';
import { eq, and } from 'drizzle-orm';
import { RESERVED_SLUGS } from '@/lib/custom-pages';

const SITE_ID = process.env.SITE_ID || 'ten-sura-game.com';

function pathToSiteId(slug: string) {
  return `${SITE_ID}/${slug}`;
}

export async function POST(request: Request) {
  try {
    const body = await request.json();
    const { title, slug, metaTitle, metaDescription, showInHeader, showInFooter } = body;

    if (!title || !slug) {
      return NextResponse.json({ error: 'Title and slug are required' }, { status: 400 });
    }

    if (RESERVED_SLUGS.includes(slug)) {
      return NextResponse.json({ error: 'Slug is reserved' }, { status: 400 });
    }

    // Insert the custom page
    const newPage = await db.insert(customPages).values({
      siteId: SITE_ID,
      title,
      slug,
      metaTitle: metaTitle || null,
      metaDescription: metaDescription || null,
      indexable: true,
      showInHeader: showInHeader || false,
      showInFooter: showInFooter || false,
      createdAt: new Date(),
      updatedAt: new Date(),
    }).returning({ id: customPages.id });

    // Initialize the canvas in homepage_content to prevent collision ghosts
    const canvasSiteId = pathToSiteId(slug);
    const emptyCanvas = {
      content: [],
      root: { props: { title } },
      zones: {},
    };
    
    await db.insert(homepageContent).values({
      siteId: canvasSiteId,
      content: emptyCanvas,
      draftContent: emptyCanvas,
      updatedAt: new Date(),
    }).onConflictDoUpdate({
      target: homepageContent.siteId,
      set: {
        content: emptyCanvas,
        draftContent: emptyCanvas,
        updatedAt: new Date()
      }
    });

    return NextResponse.json({ success: true, id: newPage[0].id });
  } catch (error: any) {
    console.error('Error creating custom page:', error);
    return NextResponse.json({ error: error.message }, { status: 500 });
  }
}

export async function PUT(request: Request) {
  try {
    const body = await request.json();
    const { id, title, metaTitle, metaDescription, indexable } = body;

    if (!id) {
      return NextResponse.json({ error: 'ID is required' }, { status: 400 });
    }

    await db.update(customPages)
      .set({
        title,
        metaTitle: metaTitle || null,
        metaDescription: metaDescription || null,
        indexable: indexable !== undefined ? indexable : true,
        updatedAt: new Date(),
      })
      .where(and(eq(customPages.id, id), eq(customPages.siteId, SITE_ID)));

    return NextResponse.json({ success: true });
  } catch (error: any) {
    console.error('Error updating custom page:', error);
    return NextResponse.json({ error: error.message }, { status: 500 });
  }
}

export async function DELETE(request: Request) {
  try {
    const { searchParams } = new URL(request.url);
    const id = searchParams.get('id');
    const slug = searchParams.get('slug');

    if (!id || !slug) {
      return NextResponse.json({ error: 'id and slug are required' }, { status: 400 });
    }

    const numericId = parseInt(id, 10);
    if (isNaN(numericId)) {
      return NextResponse.json({ error: 'Invalid id' }, { status: 400 });
    }

    // 1. Delete associated navigation items
    await db.delete(navigationItems).where(
      and(eq(navigationItems.sourceId, id), eq(navigationItems.siteId, SITE_ID))
    );

    // 2. Delete the editor canvas from homepage_content
    const canvasSiteId = pathToSiteId(slug);
    await db.delete(homepageContent).where(eq(homepageContent.siteId, canvasSiteId));

    // 3. Delete the custom page itself
    await db.delete(customPages).where(
      and(eq(customPages.id, numericId), eq(customPages.siteId, SITE_ID))
    );

    return NextResponse.json({ success: true });
  } catch (error: any) {
    console.error('Error deleting custom page:', error);
    return NextResponse.json({ error: error.message }, { status: 500 });
  }
}
