import { createServerFn } from "@tanstack/react-start";
import { z } from "zod";
import { requireSupabaseAuth } from "@/integrations/supabase/auth-middleware";

const AddStaffInput = z.object({
  companyId: z.string().uuid(),
  email: z.string().email().max(200),
  role: z.enum(["company_admin", "inspector", "technician", "agent"]),
  fullName: z.string().max(120).optional(),
});

/** Company admins add an existing account to their own company team. */
export const addCompanyStaff = createServerFn({ method: "POST" })
  .middleware([requireSupabaseAuth])
  .inputValidator((input: unknown) => AddStaffInput.parse(input))
  .handler(async ({ data, context }) => {
    const { data: allowed, error: roleError } = await context.supabase.rpc("has_company_role", {
      _user_id: context.userId,
      _company_id: data.companyId,
      _role: "company_admin",
    });
    if (roleError) throw new Error(roleError.message);
    if (!allowed) throw new Error("Only company admins can manage staff.");

    const { supabaseAdmin } = await import("@/integrations/supabase/client.server");
    const email = data.email.toLowerCase().trim();
    const { data: list, error: listError } = await supabaseAdmin.auth.admin.listUsers({ page: 1, perPage: 200 });
    if (listError) throw new Error(listError.message);
    const match = list.users.find((u) => u.email?.toLowerCase() === email);
    if (!match) throw new Error("No account found with that email. Ask them to sign up first.");

    const { error } = await context.supabase.from("company_members").insert({
      company_id: data.companyId,
      user_id: match.id,
      role: data.role,
      full_name: data.fullName || (match.user_metadata?.full_name as string | undefined) || null,
    });
    if (error) throw new Error(error.message);
    return { ok: true };
  });