import { query } from '../db/client.js'

export type FileAssetRow = {
  id: number
  object_key: string
  scene: string
  original_filename: string
  content_type: string
  size_bytes: number
  thumbnail_object_key: string
  medium_object_key: string
  url: string
  thumbnail_url: string
  medium_url: string
  uploader_type: string
  uploader_id: string
  status: string
  metadata_json: string | Record<string, unknown>
  created_at: string
  updated_at: string
}

type CreateFileAssetInput = {
  objectKey: string
  scene: string
  originalFilename: string
  contentType: string
  sizeBytes: number
  thumbnailObjectKey: string
  mediumObjectKey: string
  url: string
  thumbnailUrl: string
  mediumUrl: string
  uploaderType: string
  uploaderId: string
  metadataJson: string
  now: string
}

export async function createFileAsset(input: CreateFileAssetInput): Promise<FileAssetRow | null> {
  const result = await query<FileAssetRow>(
    `
      INSERT INTO file_assets (
        object_key, scene, original_filename, content_type, size_bytes,
        thumbnail_object_key, medium_object_key, url, thumbnail_url, medium_url,
        uploader_type, uploader_id, metadata_json, created_at, updated_at
      ) VALUES (
        $1, $2, $3, $4, $5,
        $6, $7, $8, $9, $10,
        $11, $12, $13::jsonb, $14, $15
      )
      ON CONFLICT (object_key) DO UPDATE
      SET
        scene = EXCLUDED.scene,
        original_filename = EXCLUDED.original_filename,
        content_type = EXCLUDED.content_type,
        size_bytes = EXCLUDED.size_bytes,
        thumbnail_object_key = EXCLUDED.thumbnail_object_key,
        medium_object_key = EXCLUDED.medium_object_key,
        url = EXCLUDED.url,
        thumbnail_url = EXCLUDED.thumbnail_url,
        medium_url = EXCLUDED.medium_url,
        uploader_type = EXCLUDED.uploader_type,
        uploader_id = EXCLUDED.uploader_id,
        metadata_json = EXCLUDED.metadata_json,
        updated_at = EXCLUDED.updated_at
      RETURNING *
    `,
    [
      input.objectKey,
      input.scene,
      input.originalFilename,
      input.contentType,
      input.sizeBytes,
      input.thumbnailObjectKey,
      input.mediumObjectKey,
      input.url,
      input.thumbnailUrl,
      input.mediumUrl,
      input.uploaderType,
      input.uploaderId,
      input.metadataJson,
      input.now,
      input.now,
    ],
  )
  return result.rows[0] || null
}

export async function getFileAssetByObjectKey(objectKey: string): Promise<FileAssetRow | null> {
  const result = await query<FileAssetRow>(
    'SELECT * FROM file_assets WHERE object_key = $1 AND status = $2 LIMIT 1',
    [String(objectKey || '').trim(), 'active'],
  )
  return result.rows[0] || null
}
