import { protectedProcedure, router } from "../_core/trpc.ts";
import { z } from "zod";
import { getKycDocuments, writeAuditLog, getDb, updateUser } from "../db.ts";
import { eq } from "drizzle-orm";
import { kycDocuments } from "../../drizzle/schema.ts";

export const kycRouter = router({
  getDocuments: protectedProcedure.query(async ({ ctx }) => {
    return getKycDocuments(ctx.user.id);
  }),

  submitDocument: protectedProcedure
    .input(z.object({
      docType: z.enum(["passport", "drivers_license", "national_id", "utility_bill", "bank_statement", "selfie"]),
      fileUrl: z.string().url(),
      fileKey: z.string(),
    }))
    .mutation(async ({ ctx, input }) => {
      const db = await getDb();
      if (!db) throw new Error("DB unavailable");
      await db.insert(kycDocuments).values({
        userId: ctx.user.id,
        docType: input.docType,
        fileUrl: input.fileUrl,
        fileKey: input.fileKey,
        status: "pending",
      });
      // Update user KYC status to pending
      if (ctx.user.kycStatus === "none") {
        await updateUser(ctx.user.id, { kycStatus: "pending" });
      }
      await writeAuditLog({ actorId: ctx.user.id, actorRole: "user", action: "kyc_document_submitted", category: "kyc", details: { docType: input.docType } });
      return { success: true };
    }),

  getStatus: protectedProcedure.query(async ({ ctx }) => {
    const docs = await getKycDocuments(ctx.user.id);
    return {
      kycStatus: ctx.user.kycStatus,
      kycLevel: ctx.user.kycLevel,
      documents: docs,
      isAgeVerified: ctx.user.isAgeVerified,
    };
  }),

  submitAgeVerification: protectedProcedure
    .input(z.object({ dateOfBirth: z.string(), stateCode: z.string().max(4) }))
    .mutation(async ({ ctx, input }) => {
      const dob = new Date(input.dateOfBirth);
      const age = Math.floor((Date.now() - dob.getTime()) / (365.25 * 24 * 60 * 60 * 1000));
      if (age < 18) throw new Error("You must be 18 or older to use CoinKrazy");

      // Check restricted states
      const { getRestrictedStates } = await import("../db");
      const restricted = await getRestrictedStates();
      if (restricted.some(s => s.stateCode === input.stateCode.toUpperCase())) {
        throw new Error(`CoinKrazy is not available in your state (${input.stateCode})`);
      }

      await updateUser(ctx.user.id, { isAgeVerified: true, dateOfBirth: input.dateOfBirth, stateCode: input.stateCode.toUpperCase() });
      await writeAuditLog({ actorId: ctx.user.id, actorRole: "user", action: "age_verified", category: "kyc", details: { age, stateCode: input.stateCode } });
      return { success: true, age };
    }),
});
