import { api as client } from "../auth/http";

const BASE = "/contract-templates";

export interface ContractTemplateArticle {
  id: string;
  title: string;
  body: string;
  order: number;
}

export interface ContractTemplate {
  id: string;
  code:
    | "IMPORT_BULK"
    | "EXPORT_BULK"
    | "INTERCITY_BULK"
    | "IMPORT_CONTAINER"
    | "EXPORT_CONTAINER"
    | "INTERCITY_CONTAINER";
  name: string;
  description?: string | null;
  documentTitle: string;
  whereasClauses: string[];
  articles: ContractTemplateArticle[];
  isActive: boolean;
  createdAt: string;
  updatedAt: string;
}

export interface UpdateContractTemplatePayload {
  name?: string;
  description?: string;
  documentTitle?: string;
  whereasClauses?: string[];
  isActive?: boolean;
}

export interface ArticlePayload {
  title: string;
  body: string;
  position?: number;
}

export const contractTemplatesService = {
  async list(): Promise<ContractTemplate[]> {
    const { data } = await client.get<ContractTemplate[]>(BASE);
    return data;
  },

  async getByCode(code: string): Promise<ContractTemplate> {
    const { data } = await client.get<ContractTemplate>(`${BASE}/${code}`);
    return data;
  },

  async update(
    code: string,
    payload: UpdateContractTemplatePayload,
  ): Promise<ContractTemplate> {
    const { data } = await client.patch<ContractTemplate>(
      `${BASE}/${code}`,
      payload,
    );
    return data;
  },

  async preview(code: string): Promise<{ html: string }> {
    const { data } = await client.post<{ html: string }>(
      `${BASE}/${code}/preview`,
      {},
    );
    return data;
  },

  async addArticle(code: string, payload: ArticlePayload): Promise<ContractTemplate> {
    const { data } = await client.post<ContractTemplate>(
      `${BASE}/${code}/articles`,
      payload,
    );
    return data;
  },

  async updateArticle(
    code: string,
    articleId: string,
    payload: Partial<ArticlePayload>,
  ): Promise<ContractTemplate> {
    const { data } = await client.patch<ContractTemplate>(
      `${BASE}/${code}/articles/${articleId}`,
      payload,
    );
    return data;
  },

  async removeArticle(code: string, articleId: string): Promise<ContractTemplate> {
    const { data } = await client.delete<ContractTemplate>(
      `${BASE}/${code}/articles/${articleId}`,
    );
    return data;
  },

  async replaceArticles(
    code: string,
    articles: Array<{ id?: string; title: string; body: string }>,
  ): Promise<ContractTemplate> {
    const { data } = await client.put<ContractTemplate>(
      `${BASE}/${code}/articles`,
      { articles },
    );
    return data;
  },
};
