import type { FastifyPluginAsync } from 'fastify'
import { eq } from 'drizzle-orm'
import { companies, locations } from '../../db/schema/stores.js'
import { files } from '../../db/schema/files.js'
import { ValidationError } from '../../lib/errors.js'

export const storeRoutes: FastifyPluginAsync = async (app) => {
  // --- Public branding (no auth — used on login page) ---

  app.get('/store/branding', async (_request, reply) => {
    const [store] = await app.db.select({
      name: companies.name,
      logoFileId: companies.logoFileId,
    }).from(companies).limit(1)
    if (!store) return reply.send({ name: null, hasLogo: false })
    return reply.send({ name: store.name, hasLogo: !!store.logoFileId })
  })

  app.get('/store/logo', async (_request, reply) => {
    const [store] = await app.db.select({ logoFileId: companies.logoFileId }).from(companies).limit(1)
    if (!store?.logoFileId) return reply.status(404).send({ error: { message: 'No logo configured', statusCode: 404 } })

    const [file] = await app.db.select().from(files).where(eq(files.id, store.logoFileId)).limit(1)
    if (!file) return reply.status(404).send({ error: { message: 'Logo file not found', statusCode: 404 } })

    try {
      const data = await app.storage.get(file.path)
      const ext = file.path.split('.').pop()?.toLowerCase()
      const contentTypeMap: Record<string, string> = {
        jpg: 'image/jpeg', jpeg: 'image/jpeg', png: 'image/png', webp: 'image/webp', svg: 'image/svg+xml',
      }
      return reply
        .header('Content-Type', contentTypeMap[ext ?? ''] ?? 'application/octet-stream')
        .header('Cache-Control', 'public, max-age=3600')
        .send(data)
    } catch {
      return reply.status(404).send({ error: { message: 'Logo file not readable', statusCode: 404 } })
    }
  })

  // --- Company / Store Settings ---

  app.get('/store', { preHandler: [app.authenticate, app.requirePermission('settings.view')] }, async (request, reply) => {
    const [store] = await app.db.select().from(companies).limit(1)
    if (!store) return reply.status(404).send({ error: { message: 'No store configured', statusCode: 404 } })
    return reply.send(store)
  })

  app.patch('/store', { preHandler: [app.authenticate, app.requirePermission('settings.edit')] }, async (request, reply) => {
    const input = request.body as Record<string, unknown>
    const [store] = await app.db.select({ id: companies.id }).from(companies).limit(1)
    if (!store) return reply.status(404).send({ error: { message: 'No store configured', statusCode: 404 } })

    const updates: Record<string, unknown> = { updatedAt: new Date() }
    if (input.name !== undefined) updates.name = input.name
    if (input.phone !== undefined) updates.phone = input.phone
    if (input.email !== undefined) updates.email = input.email
    if (input.address !== undefined) updates.address = input.address
    if (input.timezone !== undefined) updates.timezone = input.timezone
    if (input.logoFileId !== undefined) updates.logoFileId = input.logoFileId
    if (input.notes !== undefined) updates.notes = input.notes

    const [updated] = await app.db.update(companies).set(updates).where(eq(companies.id, store.id)).returning()
    return reply.send(updated)
  })

  // --- Locations (Stores) ---

  app.get('/locations', { preHandler: [app.authenticate, app.requirePermission('settings.view')] }, async (request, reply) => {
    const data = await app.db.select().from(locations).where(eq(locations.isActive, true)).orderBy(locations.name)
    return reply.send({ data })
  })

  app.post('/locations', { preHandler: [app.authenticate, app.requirePermission('settings.edit')] }, async (request, reply) => {
    const input = request.body as { name?: string; address?: Record<string, string>; phone?: string; email?: string; timezone?: string }
    if (!input.name?.trim()) throw new ValidationError('Location name is required')

    const [location] = await app.db.insert(locations).values({
      name: input.name.trim(),
      address: input.address,
      phone: input.phone,
      email: input.email,
      timezone: input.timezone,
    }).returning()
    return reply.status(201).send(location)
  })

  app.patch('/locations/:id', { preHandler: [app.authenticate, app.requirePermission('settings.edit')] }, async (request, reply) => {
    const { id } = request.params as { id: string }
    const input = request.body as Record<string, unknown>

    const updates: Record<string, unknown> = { updatedAt: new Date() }
    if (input.name !== undefined) updates.name = input.name
    if (input.phone !== undefined) updates.phone = input.phone
    if (input.email !== undefined) updates.email = input.email
    if (input.address !== undefined) updates.address = input.address
    if (input.timezone !== undefined) updates.timezone = input.timezone

    const [location] = await app.db.update(locations).set(updates).where(eq(locations.id, id)).returning()
    if (!location) return reply.status(404).send({ error: { message: 'Location not found', statusCode: 404 } })
    return reply.send(location)
  })

  app.delete('/locations/:id', { preHandler: [app.authenticate, app.requirePermission('settings.edit')] }, async (request, reply) => {
    const { id } = request.params as { id: string }
    const [location] = await app.db.update(locations).set({ isActive: false, updatedAt: new Date() }).where(eq(locations.id, id)).returning()
    if (!location) return reply.status(404).send({ error: { message: 'Location not found', statusCode: 404 } })
    return reply.send(location)
  })
}
