import { readFile, writeFile, mkdir, copyFile, access } from 'node:fs/promises';
import { join } from 'node:path';
import { CONTENT_SCHEMAS, type ContentKey } from '../content/schemas';
import type { z } from 'zod';

const DATA_CONTENT_DIR = join(process.cwd(), 'data', 'content');
const SEED_CONTENT_DIR = join(process.cwd(), 'public', 'content');

type ContentData<K extends ContentKey> = z.infer<(typeof CONTENT_SCHEMAS)[K]>;

async function ensureContentFile(key: ContentKey): Promise<string> {
  const target = join(DATA_CONTENT_DIR, `${key}.json`);
  try {
    await access(target);
    return target;
  } catch {
    await mkdir(DATA_CONTENT_DIR, { recursive: true });
    const seed = join(SEED_CONTENT_DIR, `${key}.json`);
    await copyFile(seed, target);
    return target;
  }
}

export async function loadContent<K extends ContentKey>(key: K): Promise<ContentData<K>> {
  const filePath = await ensureContentFile(key);
  const raw = await readFile(filePath, 'utf-8');
  const parsed = JSON.parse(raw);
  const schema = CONTENT_SCHEMAS[key];
  return schema.parse(parsed) as ContentData<K>;
}

export async function saveContent<K extends ContentKey>(
  key: K,
  data: unknown,
): Promise<ContentData<K>> {
  const schema = CONTENT_SCHEMAS[key];
  const validated = schema.parse(data) as ContentData<K>;
  const filePath = await ensureContentFile(key);
  await writeFile(filePath, JSON.stringify(validated, null, 2) + '\n', 'utf-8');
  return validated;
}

export async function loadAll() {
  const [profile, skills, experiences, formations, projects, interests, site] = await Promise.all([
    loadContent('profile'),
    loadContent('skills'),
    loadContent('experiences'),
    loadContent('formations'),
    loadContent('projects'),
    loadContent('interests'),
    loadContent('site'),
  ]);
  return { profile, skills, experiences, formations, projects, interests, site };
}
