import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

export interface PocketBaseField {
  name: string;
  type: string;
  required?: boolean;
  hidden?: boolean;
  values?: string[];
  collectionId?: string;
  maxSelect?: number;
}

export interface PocketBaseCollection {
  id: string;
  name: string;
  type: string;
  fields?: PocketBaseField[];
  schema?: PocketBaseField[];
  listRule?: string;
  viewRule?: string;
  createRule?: string;
  updateRule?: string;
  deleteRule?: string;
}

function defaultSchemaPath() {
  const moduleDir = path.dirname(fileURLToPath(import.meta.url));
  const candidates = [
    path.resolve(process.cwd(), process.env.PB_SCHEMA_PATH || ''),
    path.resolve(process.cwd(), '../../docs/pb_schema.json'),
    path.resolve(process.cwd(), 'docs/pb_schema.json'),
    path.resolve(moduleDir, '../../../docs/pb_schema.json'),
  ].filter(candidate => candidate && candidate !== process.cwd());

  return candidates.find(candidate => fs.existsSync(candidate)) || candidates[candidates.length - 1];
}

export function readPocketBaseSchema(schemaPath = process.env.PB_SCHEMA_PATH || '') {
  const absPath = schemaPath ? path.resolve(process.cwd(), schemaPath) : defaultSchemaPath();
  const raw = JSON.parse(fs.readFileSync(absPath, 'utf8'));
  const collections = (Array.isArray(raw) ? raw : raw.collections || []) as PocketBaseCollection[];
  const byId = new Map(collections.map(c => [c.id, c]));
  const byName = new Map(collections.map(c => [c.name, c]));
  return { absPath, collections, byId, byName };
}

export function fieldsOf(collection: PocketBaseCollection) {
  return collection.fields || collection.schema || [];
}
