import type { APIRoute } from 'astro';
import { query } from '../../../lib/db';

export const GET: APIRoute = async () => {
  try {
    const result = await query('SELECT * FROM homepage_sections ORDER BY sort_order ASC');
    return new Response(JSON.stringify({ sections: result.rows }), {
      headers: { 'Content-Type': 'application/json' },
    });
  } catch {
    return new Response(JSON.stringify({ sections: [] }), {
      headers: { 'Content-Type': 'application/json' },
    });
  }
};

export const PUT: APIRoute = async ({ request }) => {
  try {
    const body = await request.json();

    if (body.reorder && Array.isArray(body.ids)) {
      for (let i = 0; i < body.ids.length; i++) {
        await query('UPDATE homepage_sections SET sort_order = $1, updated_at = now() WHERE id = $2', [i, body.ids[i]]);
      }
      return new Response(JSON.stringify({ success: true }));
    }

    if (body.id) {
      await query(
        'UPDATE homepage_sections SET type = $1, title = $2, config = $3, enabled = $4, updated_at = now() WHERE id = $5',
        [body.type, body.title, JSON.stringify(body.config), body.enabled ?? true, body.id]
      );
      return new Response(JSON.stringify({ success: true }));
    }

    return new Response(JSON.stringify({ error: 'Invalid request' }), { status: 400 });
  } catch (err) {
    return new Response(JSON.stringify({ error: 'Failed to update' }), { status: 500 });
  }
};

export const POST: APIRoute = async ({ request }) => {
  try {
    const body = await request.json();
    const maxOrder = await query('SELECT COALESCE(MAX(sort_order), -1) + 1 as next FROM homepage_sections');
    const result = await query(
      'INSERT INTO homepage_sections (type, title, config, sort_order, enabled) VALUES ($1, $2, $3, $4, $5) RETURNING *',
      [body.type, body.title || '', JSON.stringify(body.config || {}), maxOrder.rows[0].next, body.enabled ?? true]
    );
    return new Response(JSON.stringify(result.rows[0]), {
      headers: { 'Content-Type': 'application/json' },
    });
  } catch (err) {
    return new Response(JSON.stringify({ error: 'Failed to create' }), { status: 500 });
  }
};

export const DELETE: APIRoute = async ({ request }) => {
  try {
    const { id } = await request.json();
    await query('DELETE FROM homepage_sections WHERE id = $1', [id]);
    return new Response(JSON.stringify({ success: true }));
  } catch {
    return new Response(JSON.stringify({ error: 'Failed to delete' }), { status: 500 });
  }
};
