import apiClient from './client'
import type {
  ScriptCategoryResponse,
  ScriptTemplateListItem,
  ScriptTemplateDetail,
  ScriptGenerateRequest,
  ScriptGenerateResponse,
  ScriptGenerationRecord,
  ScriptTemplateCreateRequest,
  ScriptTemplateUpdateRequest,
} from '@/types'

export const scriptsApi = {
  async getCategories(): Promise<ScriptCategoryResponse[]> {
    const response = await apiClient.get<ScriptCategoryResponse[]>('/scripts/categories')
    return response.data
  },

  async getTemplates(params?: {
    category_slug?: string
    search?: string
    tags?: string // Phase 3: comma-separated tag filter
    mine?: boolean
    shared?: boolean
  }): Promise<ScriptTemplateListItem[]> {
    const response = await apiClient.get<ScriptTemplateListItem[]>('/scripts/templates', { params })
    return response.data
  },

  async getTemplateDetail(id: string): Promise<ScriptTemplateDetail> {
    const response = await apiClient.get<ScriptTemplateDetail>(`/scripts/templates/${id}`)
    return response.data
  },

  async generate(req: ScriptGenerateRequest): Promise<ScriptGenerateResponse> {
    const response = await apiClient.post<ScriptGenerateResponse>('/scripts/generate', req)
    return response.data
  },

  // Phase 3: fetch generation history for the current user
  async getGenerations(): Promise<ScriptGenerationRecord[]> {
    const response = await apiClient.get<ScriptGenerationRecord[]>('/scripts/generations')
    return response.data
  },

  async getManagedTemplates(params?: {
    category_slug?: string
    search?: string
  }): Promise<ScriptTemplateListItem[]> {
    const response = await apiClient.get<ScriptTemplateListItem[]>('/scripts/templates', {
      params: { ...params, managed: true },
    })
    return response.data
  },

  async createTemplate(data: ScriptTemplateCreateRequest): Promise<ScriptTemplateDetail> {
    const response = await apiClient.post<ScriptTemplateDetail>('/scripts/templates', data)
    return response.data
  },

  async updateTemplate(id: string, data: ScriptTemplateUpdateRequest): Promise<ScriptTemplateDetail> {
    const response = await apiClient.put<ScriptTemplateDetail>(`/scripts/templates/${id}`, data)
    return response.data
  },

  async deleteTemplate(id: string): Promise<void> {
    await apiClient.delete(`/scripts/templates/${id}`)
  },

  async shareTemplate(id: string, shared: boolean): Promise<ScriptTemplateDetail> {
    const response = await apiClient.patch<ScriptTemplateDetail>(
      `/scripts/templates/${id}/share`,
      null,
      { params: { shared } },
    )
    return response.data
  },
}

export default scriptsApi
