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

const createInstanceSchema = z.object({
  name: z.string().min(2),
  baseUrl: z.string().url(),
  capabilities: z.array(z.string()).default(["ios_push", "minimal_payload"]),
  rateLimitPerMinute: z.number().int().positive().default(120),
  dailyQuota: z.number().int().positive().default(10000),
  mode: z.enum(["minimal", "rich"]).default("minimal"),
  notes: z.string().optional(),
});

const updateInstanceSchema = createInstanceSchema.partial().extend({
  status: z.enum(["active", "blocked", "disabled"]).optional(),
});

const testPushSchema = z.object({
  deviceIds: z.array(z.string().min(1)).max(100).optional(),
  title: z.string().min(1).max(120).default("FEDEO Push-Test"),
  body: z.string().min(1).max(240).default("Diese Testnachricht wurde über das Push-Admin-Dashboard gesendet."),
  priority: z.enum(["normal", "high"]).default("high"),
});

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

  app.get("/admin/summary", async () => {
    const [instances] = await db.select({ count: sql<number>`count(*)::int` }).from(pushInstances);
    const [devices] = await db.select({ count: sql<number>`count(*)::int` }).from(pushDevices);
    const [jobs] = await db.select({ count: sql<number>`count(*)::int` }).from(deliveryJobs);
    const [failedJobs] = await db.select({ count: sql<number>`count(*)::int` }).from(deliveryJobs).where(eq(deliveryJobs.status, "failed"));
    return {
      instances: instances?.count || 0,
      devices: devices?.count || 0,
      jobs: jobs?.count || 0,
      failedJobs: failedJobs?.count || 0,
    };
  });

  app.get("/admin/instances", async () => {
    const rows = await db.select().from(pushInstances).orderBy(desc(pushInstances.createdAt));
    return rows.map(publicInstance);
  });

  app.post("/admin/instances", async (request, reply) => {
    const body = createInstanceSchema.parse(request.body);
    const secret = createClientSecret();
    const [created] = await db.insert(pushInstances).values({
      instanceId: createPublicId("inst"),
      name: body.name,
      baseUrl: body.baseUrl,
      capabilities: body.capabilities,
      rateLimitPerMinute: body.rateLimitPerMinute,
      dailyQuota: body.dailyQuota,
      mode: body.mode,
      notes: body.notes,
      currentSecretEncrypted: encryptSecret(secret),
      currentSecretPreview: previewSecret(secret),
    }).returning();

    await audit("admin", "instance.created", created.id, { instanceId: created.instanceId });
    return reply.code(201).send({ ...publicInstance(created), clientSecret: secret });
  });

  app.get("/admin/instances/:id", async (request, reply) => {
    const params = z.object({ id: z.string().uuid() }).parse(request.params);
    const [instance] = await db.select().from(pushInstances).where(eq(pushInstances.id, params.id)).limit(1);
    if (!instance) return reply.code(404).send({ error: "instance_not_found" });

    const [deviceCount] = await db.select({ count: sql<number>`count(*)::int` }).from(pushDevices).where(eq(pushDevices.instanceId, instance.id));
    const [jobCount] = await db.select({ count: sql<number>`count(*)::int` }).from(deliveryJobs).where(eq(deliveryJobs.instanceId, instance.id));
    return { ...publicInstance(instance), deviceCount: deviceCount?.count || 0, jobCount: jobCount?.count || 0 };
  });

  app.patch("/admin/instances/:id", async (request, reply) => {
    const params = z.object({ id: z.string().uuid() }).parse(request.params);
    const body = updateInstanceSchema.parse(request.body);
    const [updated] = await db.update(pushInstances).set({ ...body, updatedAt: new Date() }).where(eq(pushInstances.id, params.id)).returning();
    if (!updated) return reply.code(404).send({ error: "instance_not_found" });
    await audit("admin", "instance.updated", updated.id, { fields: Object.keys(body) });
    return publicInstance(updated);
  });

  app.post("/admin/instances/:id/rotate-secret", async (request, reply) => {
    const params = z.object({ id: z.string().uuid() }).parse(request.params);
    const body = z.object({ promote: z.boolean().optional().default(false) }).parse(request.body || {});
    const [instance] = await db.select().from(pushInstances).where(eq(pushInstances.id, params.id)).limit(1);
    if (!instance) return reply.code(404).send({ error: "instance_not_found" });

    if (body.promote) {
      if (!instance.nextSecretEncrypted || !instance.nextSecretPreview) {
        return reply.code(400).send({ error: "next_secret_missing", message: "Es ist kein nächster Schlüssel hinterlegt." });
      }
      const [updated] = await db.update(pushInstances).set({
        currentSecretEncrypted: instance.nextSecretEncrypted,
        currentSecretPreview: instance.nextSecretPreview,
        nextSecretEncrypted: null,
        nextSecretPreview: null,
        updatedAt: new Date(),
      }).where(eq(pushInstances.id, instance.id)).returning();
      await audit("admin", "instance.secret.promoted", instance.id);
      return publicInstance(updated);
    }

    const nextSecret = createClientSecret();
    const [updated] = await db.update(pushInstances).set({
      nextSecretEncrypted: encryptSecret(nextSecret),
      nextSecretPreview: previewSecret(nextSecret),
      updatedAt: new Date(),
    }).where(eq(pushInstances.id, instance.id)).returning();
    await audit("admin", "instance.secret.rotated", instance.id);
    return { ...publicInstance(updated), nextClientSecret: nextSecret };
  });

  app.get("/admin/instances/:id/devices", async (request) => {
    const params = z.object({ id: z.string().uuid() }).parse(request.params);
    return await db.select().from(pushDevices).where(eq(pushDevices.instanceId, params.id)).orderBy(desc(pushDevices.createdAt));
  });

  app.get("/admin/instances/:id/jobs", async (request) => {
    const params = z.object({ id: z.string().uuid() }).parse(request.params);
    return await db.select().from(deliveryJobs).where(eq(deliveryJobs.instanceId, params.id)).orderBy(desc(deliveryJobs.createdAt)).limit(100);
  });

  app.post("/admin/instances/:id/test-push", async (request, reply) => {
    const params = z.object({ id: z.string().uuid() }).parse(request.params);
    const body = testPushSchema.parse(request.body || {});
    const [instance] = await db.select().from(pushInstances).where(eq(pushInstances.id, params.id)).limit(1);
    if (!instance) return reply.code(404).send({ error: "instance_not_found" });

    const devices = await db
      .select()
      .from(pushDevices)
      .where(and(eq(pushDevices.instanceId, instance.id), eq(pushDevices.status, "active")));
    const requested = body.deviceIds?.length ? new Set(body.deviceIds) : null;
    const acceptedDevices = devices
      .map((device) => device.centralDeviceId)
      .filter((centralDeviceId) => !requested || requested.has(centralDeviceId));

    if (!acceptedDevices.length) {
      return reply.code(400).send({ error: "no_active_devices", message: "Für diese Auswahl wurden keine aktiven Geräte gefunden." });
    }

    const rejected = requested ? body.deviceIds!.length - acceptedDevices.length : 0;
    const [job] = await db.insert(deliveryJobs).values({
      deliveryJobId: createPublicId("job"),
      instanceId: instance.id,
      idempotencyKey: `admin-test:${instance.id}:${Date.now()}`,
      priority: body.priority,
      ttlSeconds: 600,
      collapseKey: "admin-test",
      acceptedCount: acceptedDevices.length,
      rejectedCount: rejected,
      status: "processing",
    }).returning();

    await deliverJob(job, acceptedDevices, {
      priority: body.priority,
      ttlSeconds: 600,
      collapseKey: "admin-test",
      notification: {
        title: body.title,
        body: body.body,
      },
      data: {
        type: "admin.test_push",
        deliveryJobId: job.deliveryJobId,
        instanceId: instance.instanceId,
      },
    });

    await audit("admin", "instance.test_push.sent", instance.id, {
      deliveryJobId: job.deliveryJobId,
      accepted: acceptedDevices.length,
      rejected,
    });

    const [updatedJob] = await db.select().from(deliveryJobs).where(eq(deliveryJobs.id, job.id)).limit(1);
    return reply.code(202).send({
      deliveryJobId: job.deliveryJobId,
      accepted: acceptedDevices.length,
      rejected,
      status: updatedJob?.status || "processing",
      sent: updatedJob?.sentCount || 0,
      failed: updatedJob?.failedCount || 0,
      lastErrorCode: updatedJob?.lastErrorCode,
      lastErrorMessage: updatedJob?.lastErrorMessage,
    });
  });

  app.get("/admin/jobs", async () => {
    return await db.select({
      id: deliveryJobs.id,
      deliveryJobId: deliveryJobs.deliveryJobId,
      instanceId: deliveryJobs.instanceId,
      status: deliveryJobs.status,
      acceptedCount: deliveryJobs.acceptedCount,
      sentCount: deliveryJobs.sentCount,
      failedCount: deliveryJobs.failedCount,
      lastErrorCode: deliveryJobs.lastErrorCode,
      createdAt: deliveryJobs.createdAt,
    }).from(deliveryJobs).orderBy(desc(deliveryJobs.createdAt)).limit(100);
  });

  app.get("/admin/audit-logs", async (request) => {
    const query = z.object({ instanceId: z.string().uuid().optional() }).parse(request.query);
    return await db
      .select()
      .from(auditLogs)
      .where(query.instanceId ? eq(auditLogs.instanceId, query.instanceId) : undefined)
      .orderBy(desc(auditLogs.createdAt))
      .limit(100);
  });
}

function publicInstance(instance: typeof pushInstances.$inferSelect) {
  return {
    id: instance.id,
    instanceId: instance.instanceId,
    name: instance.name,
    baseUrl: instance.baseUrl,
    status: instance.status,
    mode: instance.mode,
    capabilities: instance.capabilities,
    rateLimitPerMinute: instance.rateLimitPerMinute,
    dailyQuota: instance.dailyQuota,
    currentSecretPreview: instance.currentSecretPreview,
    nextSecretPreview: instance.nextSecretPreview,
    notes: instance.notes,
    lastHeartbeatAt: instance.lastHeartbeatAt,
    lastHeartbeatVersion: instance.lastHeartbeatVersion,
    lastHeartbeatIp: instance.lastHeartbeatIp,
    createdAt: instance.createdAt,
    updatedAt: instance.updatedAt,
  };
}

async function audit(actor: string, action: string, instanceId: string | null, meta: Record<string, unknown> = {}) {
  await db.insert(auditLogs).values({ actor, action, instanceId, meta });
}
