import { sql } from '../../../lib/sql.js';
import { getUserFromRequest } from '../../../lib/permission-middleware';
import { pickDesignFields } from '../../../lib/custom-cards-fields.js';
import { syncCatalogCard, ensureOwnedRow, resolveCatalogGame } from './index.js';

export default async function handler(req, res) {
  try {
    const user = await getUserFromRequest(req);
    if (!user) {
      return res.status(401).json({ error: 'Authentication required' });
    }

    const designId = parseInt(req.query.id, 10);
    if (!Number.isInteger(designId)) {
      return res.status(400).json({ error: 'Invalid design id' });
    }

    const found = await sql`
      SELECT c.*, f.name AS frame_name, f.palette AS frame_palette, f.texture_url AS frame_texture,
             f.frame_image_url AS frame_image, f.layout AS frame_layout
      FROM custom_cards c
      LEFT JOIN custom_frames f ON f.id = c.custom_frame_id
      WHERE c.id = ${designId} AND c.user_id = ${user.userId}
    `;
    if (found.rows.length === 0) {
      return res.status(404).json({ error: 'Design not found' });
    }
    const { frame_name, frame_palette, frame_texture, frame_image, frame_layout, ...row } = found.rows[0];
    const existing = {
      ...row,
      custom_frame:
        frame_name != null
          ? {
              id: row.custom_frame_id,
              name: frame_name,
              palette: frame_palette,
              texture_url: frame_texture,
              frame_image_url: frame_image,
              layout: frame_layout,
            }
          : null,
    };

    if (req.method === 'GET') {
      return res.status(200).json({ design: existing });
    }

    if (req.method === 'PUT') {
      const f = pickDesignFields(req.body);
      if (!f.name) {
        return res.status(400).json({ error: 'Name is required' });
      }

      const updated = await sql`
        UPDATE custom_cards SET
          name = ${f.name}, mana_cost = ${f.manaCost},
          card_type = ${f.cardType}, rarity = ${f.rarity},
          rules_text = ${f.rulesText}, actions = ${f.actions},
          flavor_quote = ${f.flavorQuote},
          power = ${f.power}, toughness = ${f.toughness},
          frame_id = ${f.frameId}, artwork_url = ${f.artworkUrl},
          art_mode = ${f.artMode},
          game_target = ${f.gameTarget}, custom_game_id = ${f.customGameId},
          custom_frame_id = ${f.customFrameId},
          updated_at = CURRENT_TIMESTAMP
        WHERE id = ${designId}
        RETURNING *
      `;
      const design = updated.rows[0];

      const catalogGame = await resolveCatalogGame(user.userId, f);
      const cardId = await syncCatalogCard(design, f, catalogGame);
      if (cardId) {
        await ensureOwnedRow(user.userId, cardId);
        if (!design.card_id) {
          const linked = await sql`
            UPDATE custom_cards SET card_id = ${cardId}
            WHERE id = ${designId} RETURNING *
          `;
          return res.status(200).json({ design: linked.rows[0] });
        }
      }
      return res.status(200).json({ design });
    }

    if (req.method === 'DELETE') {
      // The catalog twin stays (it may already live in lists/decks);
      // removing the design row simply detaches future edits from it.
      await sql`DELETE FROM custom_cards WHERE id = ${designId}`;
      return res.status(200).json({ message: 'Design deleted' });
    }

    return res.status(405).json({ error: 'Method not allowed' });
  } catch (error) {
    console.error('Custom card API error:', error);
    return res.status(500).json({ error: 'Internal server error' });
  }
}
