import { apiClient } from '../api/client';

/** Research-project lifecycle status (mirrors be0 research_projects.status). */
export type ProjectStatus = 'draft' | 'submitted' | 'approved' | 'rejected';

/** A research-project proposal/project (mirrors be0 `ProjectOut`). */
export type ResearchProject = {
  id: string;
  ownerUserId: string;
  status: ProjectStatus;
  code?: string | null;
  title: string;
  level: string;
  piName: string;
  periodMonths?: number | null;
  budgetTotal?: number | null;
  content: Record<string, unknown>;
  submittedAt?: string | null;
  reviewedAt?: string | null;
  reviewNote?: string | null;
  createdAt?: string | null;
  updatedAt?: string | null;
};

export type ResearchAuditEntry = {
  id: number;
  occurredAt?: string | null;
  actorName: string;
  roleLabel: string;
  action: string;
  subject: string;
  detail: string;
};

/** The 5 cockpit entity collections (rows keyed by the cockpit field names + id/sortOrder). */
export type CockpitEntity = 'members' | 'datasets' | 'models' | 'assets' | 'milestones';
export type EntityRow = Record<string, unknown> & { id: string; sortOrder: number };

export type CockpitBundle = {
  project: ResearchProject;
  members: EntityRow[];
  datasets: EntityRow[];
  models: EntityRow[];
  assets: EntityRow[];
  milestones: EntityRow[];
  audit: ResearchAuditEntry[];
};

const BASE = '/api/v1/research';

// --- proposals lifecycle ---
export function listMyProjects(opts: { mine?: boolean } = {}): Promise<ResearchProject[]> {
  return apiClient.get<ResearchProject[]>(`${BASE}/projects`, {
    params: opts.mine === false ? { mine: false } : undefined,
  });
}

export function getProject(id: string): Promise<ResearchProject> {
  return apiClient.get<ResearchProject>(`${BASE}/projects/${encodeURIComponent(id)}`);
}

export function createProject(content: Record<string, unknown>): Promise<ResearchProject> {
  return apiClient.post<ResearchProject>(`${BASE}/projects`, { content });
}

export function updateProject(id: string, content: Record<string, unknown>): Promise<ResearchProject> {
  return apiClient.put<ResearchProject>(`${BASE}/projects/${encodeURIComponent(id)}`, { content });
}

/**
 * Shallow-merge administrative-detail fields (Hợp đồng / Kinh phí / Thời gian / Nghiệm thu …)
 * into an approved project's content. Cockpit-side counterpart to {@link updateProject}:
 * merges (does not replace) and is allowed after approval. Owner-or-admin only.
 */
export function updateProjectDetail(
  id: string,
  patch: Record<string, unknown>,
): Promise<ResearchProject> {
  return apiClient.put<ResearchProject>(`${BASE}/projects/${encodeURIComponent(id)}/detail`, { patch });
}

export function submitProject(id: string): Promise<ResearchProject> {
  return apiClient.post<ResearchProject>(`${BASE}/projects/${encodeURIComponent(id)}/submit`, {});
}

export function approveProject(
  id: string,
  body: { code?: string; note?: string } = {},
): Promise<ResearchProject> {
  return apiClient.post<ResearchProject>(`${BASE}/projects/${encodeURIComponent(id)}/approve`, body);
}

export function rejectProject(id: string, body: { note?: string } = {}): Promise<ResearchProject> {
  return apiClient.post<ResearchProject>(`${BASE}/projects/${encodeURIComponent(id)}/reject`, body);
}

export function deleteProject(id: string): Promise<{ ok: boolean }> {
  return apiClient.delete(`${BASE}/projects/${encodeURIComponent(id)}`);
}

export function listProjectAudit(id: string): Promise<ResearchAuditEntry[]> {
  return apiClient.get<ResearchAuditEntry[]>(`${BASE}/projects/${encodeURIComponent(id)}/audit`);
}

// --- cockpit entities ---
export function getCockpit(id: string): Promise<CockpitBundle> {
  return apiClient.get<CockpitBundle>(`${BASE}/projects/${encodeURIComponent(id)}/cockpit`);
}

export function listEntities(projectId: string, entity: CockpitEntity): Promise<EntityRow[]> {
  return apiClient.get<EntityRow[]>(
    `${BASE}/projects/${encodeURIComponent(projectId)}/entities/${entity}`,
  );
}

export function createEntity(
  projectId: string,
  entity: CockpitEntity,
  data: Record<string, unknown>,
): Promise<EntityRow> {
  return apiClient.post<EntityRow>(
    `${BASE}/projects/${encodeURIComponent(projectId)}/entities/${entity}`,
    data,
  );
}

export function updateEntity(
  projectId: string,
  entity: CockpitEntity,
  itemId: string,
  data: Record<string, unknown>,
): Promise<EntityRow> {
  return apiClient.put<EntityRow>(
    `${BASE}/projects/${encodeURIComponent(projectId)}/entities/${entity}/${encodeURIComponent(itemId)}`,
    data,
  );
}

export function deleteEntity(
  projectId: string,
  entity: CockpitEntity,
  itemId: string,
): Promise<{ ok: boolean }> {
  return apiClient.delete(
    `${BASE}/projects/${encodeURIComponent(projectId)}/entities/${entity}/${encodeURIComponent(itemId)}`,
  );
}

/** Vietnamese status labels for the proposal lifecycle. */
export const PROJECT_STATUS_LABEL: Record<ProjectStatus, string> = {
  draft: 'Bản thảo',
  submitted: 'Chờ phê duyệt',
  approved: 'Đã phê duyệt',
  rejected: 'Bị từ chối',
};
