import request from '@/utils/request'
import type {
  MetadataFieldDefinition,
  MetadataFieldCreateRequest,
  MetadataFieldUpdateRequest,
  MetadataFieldListResponse,
  MetadataPayload,
  MetadataScope,
  FieldRole
} from '@/types/metadata'

export const metadataSchemaApi = {
  list: (status?: 'draft' | 'active' | 'deprecated', fieldRole?: FieldRole) =>
    request<MetadataFieldDefinition[]>({ 
      method: 'GET', 
      url: '/admin/metadata-schemas', 
      params: { 
        ...(status ? { status } : {}),
        ...(fieldRole ? { field_role: fieldRole } : {})
      } 
    }),

  get: (id: string) =>
    request<MetadataFieldDefinition>({ method: 'GET', url: `/admin/metadata-schemas/${id}` }),

  create: (data: MetadataFieldCreateRequest) =>
    request<MetadataFieldDefinition>({ method: 'POST', url: '/admin/metadata-schemas', data }),

  update: (id: string, data: MetadataFieldUpdateRequest) =>
    request<MetadataFieldDefinition>({ method: 'PUT', url: `/admin/metadata-schemas/${id}`, data }),

  delete: (id: string) =>
    request({ method: 'DELETE', url: `/admin/metadata-schemas/${id}` }),

  getByScope: (scope: MetadataScope, includeDeprecated = false) =>
    request<MetadataFieldListResponse>({
      method: 'GET',
      url: '/admin/metadata-schemas',
      params: { scope, include_deprecated: includeDeprecated }
    }),

  getByRole: (role: FieldRole, includeDeprecated = false) =>
    request<MetadataFieldListResponse>({
      method: 'GET',
      url: '/admin/metadata-schemas/by-role',
      params: { role, include_deprecated: includeDeprecated }
    }),

  validate: (metadata: MetadataPayload, scope?: MetadataScope) =>
    request<{ valid: boolean; errors?: { field_key: string; message: string }[] }>({
      method: 'POST',
      url: '/admin/metadata-schemas/validate',
      data: { metadata, scope }
    }),

  checkCompatibility: (oldScope: MetadataScope, newScope: MetadataScope, metadata: MetadataPayload) =>
    request<{
      compatible: boolean;
      conflicts: { field_key: string; reason: string }[];
      preserved_keys: string[]
    }>({
      method: 'POST',
      url: '/admin/metadata-schemas/check-compatibility',
      data: { old_scope: oldScope, new_scope: newScope, metadata }
    })
}

export type {
  MetadataFieldDefinition,
  MetadataFieldCreateRequest,
  MetadataFieldUpdateRequest,
  MetadataFieldListResponse,
  MetadataPayload
}
