import { Router, Response } from 'express';
import { z } from 'zod';
import prisma from '../lib/prisma.js';
import { authenticateToken, AuthRequest } from '../middleware/auth.middleware.js';

const router = Router();

const draftStepSchema = z.enum(['basic', 'details', 'location', 'photos', 'review']);

const upsertDraftSchema = z.object({
  listingType: z.enum(['SALE', 'RENT']).optional(),
  payload: z.any().optional(),
  photos: z.any().optional(),
  activeStep: draftStepSchema.optional(),
  lastError: z.string().optional(),
});

router.get('/my', authenticateToken, async (req: AuthRequest, res: Response) => {
  try {
    const userId = req.userId;
    if (!userId) return res.status(401).json({ error: 'Authentication required.' });

    const drafts = await (prisma as any).propertyDraft.findMany({
      where: { userId },
      select: {
        id: true,
        userId: true,
        listingType: true,
        payload: true,
        photos: true,
        activeStep: true,
        lastError: true,
        createdAt: true,
        updatedAt: true,
      },
      orderBy: { updatedAt: 'desc' },
    });

    res.json({ drafts });
  } catch (error: any) {
    console.error('Property draft get error:', error);
    res.status(500).json({ error: 'Failed to load drafts', message: error.message });
  }
});

router.post('/', authenticateToken, async (req: AuthRequest, res: Response) => {
  try {
    const userId = req.userId;
    if (!userId) return res.status(401).json({ error: 'Authentication required.' });

    const parsed = upsertDraftSchema.parse(req.body || {});

    // Attempt to create a new draft. Some databases still have a legacy
    // unique constraint on (user_id), so we gracefully fall back to
    // returning the existing draft if that constraint is hit.
    const draft = await (prisma as any).propertyDraft.create({
      data: {
        userId,
        listingType: parsed.listingType || 'SALE',
        payload: parsed.payload ?? undefined,
        photos: parsed.photos ?? undefined,
        activeStep: parsed.activeStep || 'basic',
        lastError: parsed.lastError ?? null,
      },
      select: {
        id: true,
        userId: true,
        listingType: true,
        payload: true,
        photos: true,
        activeStep: true,
        lastError: true,
        createdAt: true,
        updatedAt: true,
      },
    });

    res.json({ draft });
  } catch (error: any) {
    console.error('Property draft create error:', error);

    // Handle legacy unique constraint on property_drafts.user_id gracefully.
    if (error?.code === 'P2002' && error.meta?.target === 'property_drafts_user_id_key') {
      try {
        const existing = await (prisma as any).propertyDraft.findFirst({
          where: { userId: (req as AuthRequest).userId },
          select: {
            id: true,
            userId: true,
            listingType: true,
            payload: true,
            photos: true,
            activeStep: true,
            lastError: true,
            createdAt: true,
            updatedAt: true,
          },
          orderBy: { updatedAt: 'desc' },
        });

        if (existing) {
          return res.json({ draft: existing });
        }
      } catch (nestedErr: any) {
        console.error('Property draft fallback findFirst error:', nestedErr);
      }
    }

    res.status(500).json({ error: 'Failed to create draft', message: error.message });
  }
});

router.put('/:id', authenticateToken, async (req: AuthRequest, res: Response) => {
  try {
    const userId = req.userId;
    if (!userId) return res.status(401).json({ error: 'Authentication required.' });

    const { id } = req.params;
    const parsed = upsertDraftSchema.parse(req.body || {});

    const existing = await (prisma as any).propertyDraft.findUnique({ where: { id } });
    if (!existing || existing.userId !== userId) {
      return res.status(404).json({ error: 'Draft not found' });
    }

    const draft = await (prisma as any).propertyDraft.update({
      where: { id },
      data: {
        listingType: parsed.listingType ?? undefined,
        payload: parsed.payload ?? undefined,
        photos: parsed.photos ?? undefined,
        activeStep: parsed.activeStep ?? undefined,
        lastError: parsed.lastError ?? null,
      },
      select: {
        id: true,
        userId: true,
        listingType: true,
        payload: true,
        photos: true,
        activeStep: true,
        lastError: true,
        createdAt: true,
        updatedAt: true,
      },
    });

    res.json({ draft });
  } catch (error: any) {
    console.error('Property draft update error:', error);
    res.status(500).json({ error: 'Failed to update draft', message: error.message });
  }
});

router.delete('/:id', authenticateToken, async (req: AuthRequest, res: Response) => {
  try {
    const userId = req.userId;
    if (!userId) return res.status(401).json({ error: 'Authentication required.' });

    const { id } = req.params;
    const existing = await (prisma as any).propertyDraft.findUnique({ where: { id } });
    if (!existing || existing.userId !== userId) {
      return res.status(404).json({ error: 'Draft not found' });
    }

    await (prisma as any).propertyDraft.delete({ where: { id } });
    res.json({ message: 'Draft deleted' });
  } catch (error: any) {
    console.error('Property draft delete error:', error);
    res.status(500).json({ error: 'Failed to delete draft', message: error.message });
  }
});

export default router;
