import { Router, Request, Response } from 'express';
import { discoverTableIds, fetchAllRecords, createRecord, updateRecord, deleteRecord } from '../services/nocodbClient';

const router = Router();

async function getSeasonsTableId(): Promise<string> {
  const tables = await discoverTableIds();
  const id = tables['Seasons'];
  if (!id) throw new Error("NocoDB table 'Seasons' not found");
  return id;
}

// GET /api/seasons
router.get('/', async (_req: Request, res: Response) => {
  try {
    const tableId = await getSeasonsTableId();
    const records = await fetchAllRecords(tableId);
    res.json(records);
  } catch (err) {
    console.error('Failed to fetch seasons:', (err as Error).message);
    res.status(500).json({ error: (err as Error).message });
  }
});

// POST /api/seasons
router.post('/', async (req: Request, res: Response) => {
  try {
    const tableId = await getSeasonsTableId();
    const result = await createRecord(tableId, req.body);
    res.json(result);
  } catch (err) {
    console.error('Failed to create season:', (err as Error).message);
    res.status(500).json({ error: (err as Error).message });
  }
});

// PUT /api/seasons/:id
router.put('/:id', async (req: Request, res: Response) => {
  try {
    const tableId = await getSeasonsTableId();
    const id = parseInt(req.params.id);
    const result = await updateRecord(tableId, id, req.body);
    res.json(result);
  } catch (err) {
    console.error('Failed to update season:', (err as Error).message);
    res.status(500).json({ error: (err as Error).message });
  }
});

// DELETE /api/seasons/:id
router.delete('/:id', async (req: Request, res: Response) => {
  try {
    const tableId = await getSeasonsTableId();
    const id = parseInt(req.params.id);
    await deleteRecord(tableId, id);
    res.json({ ok: true });
  } catch (err) {
    console.error('Failed to delete season:', (err as Error).message);
    res.status(500).json({ error: (err as Error).message });
  }
});

export default router;
