import express from 'express';
import { Request, Response } from 'express';
import { pool } from '../config/db';
import { Player } from '../models/Player';
import { createLogger } from '../utils/logger';

const router = express.Router();
const logger = createLogger('playerRoutes');

router.post('/:player', async (req: Request, res: Response) => {
  const { player } = req.params;
  try {
    // Check if player already exists
    let result = await pool.query<Player>('SELECT id, name FROM player WHERE name = $1', [player]);

    // If player doesn't exist, create new player
    if (result.rows.length === 0) {
      result = await pool.query<Player>(
        'INSERT INTO player (name) VALUES ($1) RETURNING id, name',
        [player]
      );
      logger.info(`Created new player: ${player} with ID: ${result.rows[0].id}`);
    }

    const playerData = result.rows[0] as Player;
    logger.info(`Player data:`, playerData);

    res.json(playerData);
  } catch (err) {
    logger.error('Error creating/fetching player', err);
    res.status(500).json({ error: 'Internal Server Error' });
  }
});

export default router;
