import type { FastifyInstance } from "fastify";
import { and, eq } from "drizzle-orm";
import { z } from "zod";
import { deliveryJobs, pushDevices, pushInstances } from "@fedeo/push-db";
import { db } from "../db/client.js";
import { requireInstance } from "../lib/auth.js";
import { encryptSecret } from "../lib/crypto.js";
import { createPublicId } from "../lib/ids.js";
import { deliverJob } from "../services/delivery.js";

const heartbeatSchema = z.object({
  fedeoVersion: z.string().optional(),
  baseUrl: z.string().url().optional(),
  capabilities: z.array(z.string()).optional(),
});

const deviceSchema = z.object({
  localDeviceId: z.string().min(1),
  platform: z.enum(["web", "ios", "android"]),
  providerToken: z.string().optional(),
  subscription: z.record(z.string(), z.unknown()).optional(),
  meta: z.record(z.string(), z.unknown()).optional().default({}),
});

const pushSchema = z.object({
  idempotencyKey: z.string().min(1).max(200),
  devices: z.array(z.string().min(1)).min(1).max(500),
  priority: z.enum(["normal", "high"]).default("normal"),
  ttlSeconds: z.number().int().positive().max(2_419_200).default(3600),
  collapseKey: z.string().max(64).optional(),
  notification: z.object({
    title: z.string().max(120).optional(),
    body: z.string().max(240).optional(),
  }).optional(),
  data: z.record(z.string(), z.unknown()).optional().default({}),
});

export async function instanceRoutes(app: FastifyInstance): Promise<void> {
  app.addHook("preHandler", requireInstance);

  app.post("/v1/instances/heartbeat", async (request) => {
    const instance = request.pushInstance!;
    const body = heartbeatSchema.parse(request.body);
    const [updated] = await db.update(pushInstances).set({
      baseUrl: body.baseUrl || instance.baseUrl,
      capabilities: body.capabilities || instance.capabilities,
      lastHeartbeatAt: new Date(),
      lastHeartbeatVersion: body.fedeoVersion || null,
      lastHeartbeatIp: request.ip,
      updatedAt: new Date(),
    }).where(eq(pushInstances.id, instance.id)).returning();
    return {
      status: updated.status,
      instanceId: updated.instanceId,
      payloadMode: updated.mode,
      capabilities: updated.capabilities,
    };
  });

  app.post("/v1/devices", async (request) => {
    const instance = request.pushInstance!;
    const body = deviceSchema.parse(request.body);
    const existing = await db
      .select()
      .from(pushDevices)
      .where(and(eq(pushDevices.instanceId, instance.id), eq(pushDevices.localDeviceId, body.localDeviceId)))
      .limit(1);

    const values = {
      platform: body.platform,
      status: "active" as const,
      providerTokenEncrypted: body.providerToken ? encryptSecret(body.providerToken) : null,
      webPushSubscription: body.subscription || null,
      meta: body.meta,
      lastSeenAt: new Date(),
      disabledAt: null,
      updatedAt: new Date(),
    };

    if (existing[0]) {
      const [updated] = await db.update(pushDevices).set(values).where(eq(pushDevices.id, existing[0].id)).returning();
      return { centralDeviceId: updated.centralDeviceId, status: updated.status };
    }

    const [created] = await db.insert(pushDevices).values({
      ...values,
      centralDeviceId: createPublicId("dev"),
      instanceId: instance.id,
      localDeviceId: body.localDeviceId,
    }).returning();
    return { centralDeviceId: created.centralDeviceId, status: created.status };
  });

  app.delete("/v1/devices/:centralDeviceId", async (request, reply) => {
    const instance = request.pushInstance!;
    const params = z.object({ centralDeviceId: z.string().min(1) }).parse(request.params);
    const [updated] = await db.update(pushDevices).set({
      status: "disabled",
      disabledAt: new Date(),
      updatedAt: new Date(),
    }).where(and(eq(pushDevices.instanceId, instance.id), eq(pushDevices.centralDeviceId, params.centralDeviceId))).returning();
    if (!updated) return reply.code(404).send({ error: "device_not_found" });
    return { centralDeviceId: updated.centralDeviceId, status: updated.status };
  });

  app.post("/v1/push", async (request, reply) => {
    const instance = request.pushInstance!;
    const body = pushSchema.parse(request.body);
    const existing = await db
      .select()
      .from(deliveryJobs)
      .where(and(eq(deliveryJobs.instanceId, instance.id), eq(deliveryJobs.idempotencyKey, body.idempotencyKey)))
      .limit(1);

    if (existing[0]) {
      return {
        accepted: existing[0].acceptedCount,
        rejected: existing[0].rejectedCount,
        deliveryJobId: existing[0].deliveryJobId,
        status: existing[0].status,
        idempotent: true,
      };
    }

    const devices = await db
      .select()
      .from(pushDevices)
      .where(and(eq(pushDevices.instanceId, instance.id), eq(pushDevices.status, "active")));
    const allowed = new Set(devices.map((device) => device.centralDeviceId));
    const acceptedDevices = body.devices.filter((deviceId) => allowed.has(deviceId));
    const rejected = body.devices.length - acceptedDevices.length;

    const [job] = await db.insert(deliveryJobs).values({
      deliveryJobId: createPublicId("job"),
      instanceId: instance.id,
      idempotencyKey: body.idempotencyKey,
      priority: body.priority,
      ttlSeconds: body.ttlSeconds,
      collapseKey: body.collapseKey,
      acceptedCount: acceptedDevices.length,
      rejectedCount: rejected,
      status: "processing",
    }).returning();

    await deliverJob(job, acceptedDevices, {
      priority: body.priority,
      ttlSeconds: body.ttlSeconds,
      collapseKey: body.collapseKey,
      notification: body.notification,
      data: body.data,
    });

    return reply.code(202).send({
      accepted: acceptedDevices.length,
      rejected,
      deliveryJobId: job.deliveryJobId,
    });
  });

  app.get("/v1/push/:deliveryJobId", async (request, reply) => {
    const instance = request.pushInstance!;
    const params = z.object({ deliveryJobId: z.string().min(1) }).parse(request.params);
    const [job] = await db
      .select()
      .from(deliveryJobs)
      .where(and(eq(deliveryJobs.instanceId, instance.id), eq(deliveryJobs.deliveryJobId, params.deliveryJobId)))
      .limit(1);
    if (!job) return reply.code(404).send({ error: "job_not_found" });
    return {
      deliveryJobId: job.deliveryJobId,
      status: job.status,
      accepted: job.acceptedCount,
      rejected: job.rejectedCount,
      sent: job.sentCount,
      failed: job.failedCount,
      lastErrorCode: job.lastErrorCode,
      lastErrorMessage: job.lastErrorMessage,
      completedAt: job.completedAt,
    };
  });
}
