import api, { unwrap } from './request';

export interface AttachmentMeta extends Record<string, unknown> {
  attachmentId: number;
  refType: string;
  refId: number;
  originalName: string;
  storedPath: string;
  fileSize: number;
  mimeType: string;
  uploadedBy: number;
  uploaderName: string;
  uploadedAt: string;
}

export const attachmentApi = {
  list: (refType: string, refId: number) =>
    unwrap<AttachmentMeta[]>(
      api.get('/api/attachments', { params: { refType, refId } }),
    ),
  upload: (refType: string, refId: number, file: File, onProgress?: (pct: number) => void) => {
    const form = new FormData();
    form.append('file', file);
    form.append('refType', refType);
    form.append('refId', String(refId));
    return unwrap<AttachmentMeta>(
      api.post('/api/attachments', form, {
        headers: { 'Content-Type': 'multipart/form-data' },
        onUploadProgress: (evt) => {
          if (onProgress && evt.total) {
            onProgress(Math.round((evt.loaded / evt.total) * 100));
          }
        },
      }),
    );
  },
  delete: (id: number) =>
    unwrap<void>(api.delete(`/api/attachments/${id}`)),
};
