import { Router } from 'express'
import { z } from 'zod'
import { prisma } from '../lib/prisma'
import { requireRenterAuth } from '../middleware/requireRenterAuth'

const router = Router()

router.post('/signup', async (_req, res) => {
  res.status(403).json({
    error: 'renter_signup_disabled',
    message: 'Renter account creation is disabled. Only company owners can sign in to the platform.',
    statusCode: 403,
  })
})

router.post('/login', async (_req, res) => {
  res.status(403).json({
    error: 'renter_login_disabled',
    message: 'Renter sign-in is disabled. Only company owners can sign in to the platform.',
    statusCode: 403,
  })
})

router.get('/me', requireRenterAuth, async (req, res, next) => {
  try {
    const renter = await prisma.renter.findUniqueOrThrow({
      where: { id: req.renterId },
      select: {
        id: true,
        firstName: true,
        lastName: true,
        email: true,
        phone: true,
        preferredLocale: true,
        preferredCurrency: true,
        emailVerified: true,
        savedCompanies: {
          select: {
            companyId: true,
          },
        },
      },
    })

    const savedCompanyIds = renter.savedCompanies.map((saved) => saved.companyId)
    const companies = savedCompanyIds.length === 0
      ? []
      : await prisma.company.findMany({
          where: { id: { in: savedCompanyIds } },
          select: {
            id: true,
            brand: {
              select: {
                displayName: true,
                subdomain: true,
                logoUrl: true,
              },
            },
          },
        })

    const companyMap = new Map(companies.map((company) => [company.id, company]))

    const data = {
      ...renter,
      savedCompanies: renter.savedCompanies.map((saved) => ({
        id: saved.companyId,
        brand: companyMap.get(saved.companyId)?.brand ?? null,
      })),
    }
    res.json({ data })
  } catch (err) { next(err) }
})

router.patch('/me', requireRenterAuth, async (req, res, next) => {
  try {
    const body = z.object({
      firstName:         z.string().min(1).max(100).trim().optional(),
      lastName:          z.string().min(1).max(100).trim().optional(),
      phone:             z.string().max(30).trim().optional(),
      preferredLocale:   z.enum(['en', 'fr', 'ar']).optional(),
      preferredCurrency: z.enum(['MAD', 'USD', 'EUR']).optional(),
    }).parse(req.body)

    const renter = await prisma.renter.update({ where: { id: req.renterId }, data: body })
    res.json({ data: renter })
  } catch (err) { next(err) }
})

router.post('/me/fcm-token', requireRenterAuth, async (req, res, next) => {
  try {
    const { fcmToken } = z.object({ fcmToken: z.string() }).parse(req.body)
    await prisma.renter.update({ where: { id: req.renterId }, data: { fcmToken } })
    res.json({ data: { success: true } })
  } catch (err) { next(err) }
})

export default router
