import { FastifyInstance } from 'fastify'
import { StaffTimeEntryConnect } from '../../types/staff'
import { asc, eq } from "drizzle-orm";
import { stafftimenetryconnects } from "../../../db/schema";

export default async function staffTimeConnectRoutes(server: FastifyInstance) {

    // ▶ Connect anlegen
    server.post<{ Params: { id: string }, Body: Omit<StaffTimeEntryConnect, 'id' | 'time_entry_id'> }>(
        '/staff/time/:id/connects',
        async (req, reply) => {
            const { id } = req.params
            const { started_at, stopped_at, project_id, notes } = req.body
            const parsedProjectId = project_id ? Number(project_id) : null

            const data = await server.db
                .insert(stafftimenetryconnects)
                .values({
                    stafftimeentry: id,
                    started_at: new Date(started_at),
                    stopped_at: new Date(stopped_at),
                    project_id: parsedProjectId,
                    notes
                })
                .returning()

            return reply.send(data[0])
        }
    )

    // ▶ Connects abrufen
    server.get<{ Params: { id: string } }>(
        '/staff/time/:id/connects',
        async (req, reply) => {
            const { id } = req.params
            const data = await server.db
                .select()
                .from(stafftimenetryconnects)
                .where(eq(stafftimenetryconnects.stafftimeentry, id))
                .orderBy(asc(stafftimenetryconnects.started_at))

            return reply.send(data)
        }
    )

    // ▶ Connect aktualisieren
    server.patch<{ Params: { connectId: string }, Body: Partial<StaffTimeEntryConnect> }>(
        '/staff/time/connects/:connectId',
        async (req, reply) => {
            const { connectId } = req.params
            const patchData = { ...req.body } as any
            if (patchData.started_at) patchData.started_at = new Date(patchData.started_at)
            if (patchData.stopped_at) patchData.stopped_at = new Date(patchData.stopped_at)
            if (patchData.project_id !== undefined) {
                patchData.project_id = patchData.project_id ? Number(patchData.project_id) : null
            }

            const data = await server.db
                .update(stafftimenetryconnects)
                .set({ ...patchData, updated_at: new Date() })
                .where(eq(stafftimenetryconnects.id, connectId))
                .returning()

            return reply.send(data[0])
        }
    )

    // ▶ Connect löschen
    server.delete<{ Params: { connectId: string } }>(
        '/staff/time/connects/:connectId',
        async (req, reply) => {
            const { connectId } = req.params
            await server.db
                .delete(stafftimenetryconnects)
                .where(eq(stafftimenetryconnects.id, connectId))

            return reply.send({ success: true })
        }
    )
}
