import { FastifyInstance } from "fastify";
import prisma from "../../config/database";
import { requirePermission } from "../../middleware/auth";
import { logAudit } from "../../services/audit";
import { success, error, parseId } from "../../utils/response";
import { parseBody } from "../../schemas/common";
import {
  CreateBankAccountSchema,
  UpdateBankAccountSchema,
} from "../../schemas/bank-accounts.schema";

export default async function bankAccountsRoutes(
  fastify: FastifyInstance,
): Promise<void> {
  fastify.get(
    "/",
    { preHandler: requirePermission("settings.banking") },
    async (_request, reply) => {
      const accounts = await prisma.bank_accounts.findMany({
        orderBy: { position: "asc" },
      });
      return success(reply, accounts);
    },
  );

  fastify.post(
    "/",
    { preHandler: requirePermission("settings.banking") },
    async (request, reply) => {
      const parsed = parseBody(CreateBankAccountSchema, request.body);
      if ("error" in parsed) return error(reply, parsed.error, 400);
      const body = parsed.data;
      const account = await prisma.bank_accounts.create({
        data: {
          account_name: body.account_name ? String(body.account_name) : null,
          bank_name: body.bank_name ? String(body.bank_name) : null,
          account_number: body.account_number
            ? String(body.account_number)
            : null,
          iban: body.iban ? String(body.iban) : null,
          bic: body.bic ? String(body.bic) : null,
          currency: body.currency ? String(body.currency) : "CZK",
          is_default: !!body.is_default,
          position: body.position ? Number(body.position) : 0,
        },
      });

      await logAudit({
        request,
        authData: request.authData,
        action: "create",
        entityType: "bank_account",
        entityId: account.id,
        description: `Vytvořen bankovní účet ${account.account_name}`,
      });
      return success(reply, { id: account.id }, 201, "Bankovní účet vytvořen");
    },
  );

  fastify.put<{ Params: { id: string } }>(
    "/:id",
    { preHandler: requirePermission("settings.banking") },
    async (request, reply) => {
      const id = parseId(request.params.id, reply);
      if (id === null) return;
      const parsed = parseBody(UpdateBankAccountSchema, request.body);
      if ("error" in parsed) return error(reply, parsed.error, 400);
      const body = parsed.data;

      const existing = await prisma.bank_accounts.findUnique({ where: { id } });
      if (!existing) return error(reply, "Účet nenalezen", 404);

      await prisma.bank_accounts.update({
        where: { id },
        data: {
          account_name:
            body.account_name !== undefined
              ? body.account_name
                ? String(body.account_name)
                : null
              : undefined,
          bank_name:
            body.bank_name !== undefined
              ? body.bank_name
                ? String(body.bank_name)
                : null
              : undefined,
          account_number:
            body.account_number !== undefined
              ? body.account_number
                ? String(body.account_number)
                : null
              : undefined,
          iban:
            body.iban !== undefined
              ? body.iban
                ? String(body.iban)
                : null
              : undefined,
          bic:
            body.bic !== undefined
              ? body.bic
                ? String(body.bic)
                : null
              : undefined,
          currency:
            body.currency !== undefined ? String(body.currency) : undefined,
          is_default:
            body.is_default !== undefined ? !!body.is_default : undefined,
          position:
            body.position !== undefined ? Number(body.position) : undefined,
          modified_at: new Date(),
        },
      });
      await logAudit({
        request,
        authData: request.authData,
        action: "update",
        entityType: "bank_account",
        entityId: id,
        description: `Upraven bankovní účet`,
      });
      return success(reply, { id }, 200, "Bankovní účet uložen");
    },
  );

  fastify.delete<{ Params: { id: string } }>(
    "/:id",
    { preHandler: requirePermission("settings.banking") },
    async (request, reply) => {
      const id = parseId(request.params.id, reply);
      if (id === null) return;
      const existing = await prisma.bank_accounts.findUnique({ where: { id } });
      if (!existing) return error(reply, "Účet nenalezen", 404);

      await prisma.bank_accounts.delete({ where: { id } });
      await logAudit({
        request,
        authData: request.authData,
        action: "delete",
        entityType: "bank_account",
        entityId: id,
        description: `Smazán bankovní účet`,
      });
      return success(reply, null, 200, "Účet smazán");
    },
  );
}
