import fs from 'fs/promises';
import path from 'path';
import { Portal, Card } from '@/types';

const DATA_DIR = path.join(process.cwd(), 'data');
const PORTALS_FILE = path.join(DATA_DIR, 'portals.txt');
const CARDS_FILE = path.join(DATA_DIR, 'cards.txt');

// Helper to ensure files exist
async function ensureDb() {
  try { await fs.access(DATA_DIR); } catch { await fs.mkdir(DATA_DIR); }
  try { await fs.access(PORTALS_FILE); } catch { await fs.writeFile(PORTALS_FILE, '[]'); }
  try { await fs.access(CARDS_FILE); } catch { await fs.writeFile(CARDS_FILE, '[]'); }
}

export async function getPortals(): Promise<Portal[]> {
  await ensureDb();
  const data = await fs.readFile(PORTALS_FILE, 'utf-8');
  return JSON.parse(data || '[]');
}

export async function getCards(portalId?: string): Promise<Card[]> {
  await ensureDb();
  const data = await fs.readFile(CARDS_FILE, 'utf-8');
  let cards: Card[] = JSON.parse(data || '[]');

  // Backward-compat: convert old string[] extraImages → MediaItem[] extraMedia
  cards = cards.map(c => {
    const legacy = (c as any).extraImages;
    if (Array.isArray(legacy) && !c.extraMedia) {
      c.extraMedia = legacy.map((url: string) => ({ url }));
      delete (c as any).extraImages;
    }
    return c;
  });

  if (portalId) {
    cards = cards.filter(c => c.portalId === portalId);
  }

  return cards.sort((a, b) => a.displayOrder - b.displayOrder);
}

export async function saveCards(cards: Card[]): Promise<void> {
  await ensureDb();
  await fs.writeFile(CARDS_FILE, JSON.stringify(cards, null, 2));
}

// Seed function for "Casa della scuola"
export async function seedDatabase() {
  const portalId = 'uuid-casa-della-scuola';
  const portals: Portal[] = [{
    id: portalId,
    tenantId: 'casa-della-scuola',
    title: 'Benvenuti alla Casa della Scuola',
    welcomeText: 'Discover the rich history and beautiful landscapes of our heritage.',
    heroImageUrl: '/hero-bg.jpg',
    logoUrl: '/logo.png',
    themeColor: '#1e3a8a'
  }];

  const cards: Card[] = [
    {
      id: 'uuid-card-1', portalId, title: 'History before the war', 
      imageUrl: '/history.jpg', shortDescription: 'Explore the origins.',
      fullContent: '<p>Long text about the history...</p>', cardType: 'INFO_PAGE', displayOrder: 1
    },
    {
      id: 'uuid-card-2', portalId, title: 'Pettinicchio Biography', 
      imageUrl: '/pettinicchio.jpg', shortDescription: 'Life and legacy.',
      fullContent: '<p>Biography details...</p>', cardType: 'INFO_PAGE', displayOrder: 2
    },
    {
      id: 'uuid-card-3', portalId, title: 'Campobasso Landscapes', 
      imageUrl: '/campobasso.jpg', shortDescription: 'Scenic views of the region.',
      fullContent: '', cardType: 'IMAGE_GALLERY', displayOrder: 3
    }
  ];

  await fs.writeFile(PORTALS_FILE, JSON.stringify(portals, null, 2));
  await fs.writeFile(CARDS_FILE, JSON.stringify(cards, null, 2));
}

export async function savePortals(portals: Portal[]): Promise<void> {
  const fs = require('fs/promises');
  const path = require('path');
  const PORTALS_FILE = path.join(process.cwd(), 'data', 'portals.txt');
  await fs.writeFile(PORTALS_FILE, JSON.stringify(portals, null, 2));
}