import { queryOptions } from "@tanstack/react-query";
import { jsonQuery, paginatedJsonQuery } from "../apiAdapter";
import apiFetch from "../../utils/api";

export interface ProjectNote {
  id: number;
  content: string;
  user_name: string;
  created_at: string;
}

export interface ProjectData {
  id: number;
  project_number: string;
  name: string;
  status: string;
  start_date: string;
  end_date: string;
  customer_name: string;
  responsible_user_id: string;
  notes?: string;
  order_id?: number;
  order_number?: string;
  order_status?: string;
  quotation_id?: number;
  quotation_number?: string;
  has_nas_folder?: boolean;
  project_notes?: ProjectNote[];
}

export interface Project {
  id: number;
  project_number: string;
  name: string;
}

export const projectListOptions = (filters: {
  search?: string;
  sort?: string;
  order?: string;
  page?: number;
  perPage?: number;
  status?: string;
}) =>
  queryOptions({
    queryKey: ["projects", "list", filters],
    queryFn: () => {
      const params = new URLSearchParams();
      if (filters.search) params.set("search", filters.search);
      if (filters.sort) params.set("sort", filters.sort);
      if (filters.order) params.set("order", filters.order);
      if (filters.page) params.set("page", String(filters.page));
      if (filters.perPage) params.set("per_page", String(filters.perPage));
      if (filters.status) params.set("status", filters.status);
      const qs = params.toString();
      return paginatedJsonQuery<Project>(
        `/api/admin/projects${qs ? `?${qs}` : ""}`,
      );
    },
  });

export const projectDetailOptions = (id: string | undefined) =>
  queryOptions({
    queryKey: ["projects", id],
    queryFn: () => jsonQuery<ProjectData>(`/api/admin/projects/${id}`),
    enabled: !!id,
  });

export interface ProjectFilesData {
  items: Array<{
    name: string;
    type: "file" | "folder";
    size?: number;
    size_formatted?: string;
    modified?: string;
    extension?: string;
    item_count?: number;
    is_symlink?: boolean;
    link_target?: string;
  }>;
  breadcrumb: string[];
  path: string;
  full_path: string;
}

export const projectFilesOptions = (projectId: number, path: string) =>
  queryOptions({
    queryKey: ["projects", String(projectId), "files", path],
    queryFn: async (): Promise<ProjectFilesData> => {
      const params = new URLSearchParams({ project_id: String(projectId) });
      if (path) params.set("path", path);
      let res: Response;
      try {
        res = await apiFetch(`/api/admin/project-files?${params}`);
      } catch {
        throw new Error("Chyba připojení");
      }
      if (res.status === 401) throw new Error("Unauthorized");
      if (res.status === 404) {
        return { items: [], breadcrumb: [""], path: "", full_path: "" };
      }
      const data = await res.json();
      if (!res.ok || !data.success) {
        throw new Error(data.error || `Request failed (${res.status})`);
      }
      return {
        items: data.data.items || [],
        breadcrumb: data.data.breadcrumb || [""],
        path: data.data.path || "",
        full_path: data.data.full_path || "",
      };
    },
  });

export const projectNextNumberOptions = () =>
  queryOptions({
    queryKey: ["projects", "next-number"],
    queryFn: () =>
      jsonQuery<{ next_number?: string; number?: string }>(
        "/api/admin/projects/next-number",
      ),
  });
