import { Request, Response } from 'express';
import { AppDataSource } from '../data-source';
import { Country } from '../entity/Country';

export const createCountry = async (req: Request, res: Response) => {
  try {
    const { name, iso_code, phone_code } = req.body;
    const repo = AppDataSource.getRepository(Country);
    const country = repo.create({ name, iso_code, phone_code });
    const saved = await repo.save(country);
    res.status(201).json(saved);
  } catch (e) {
    res.status(500).json({ message: 'Failed to create country', error: e });
  }
};

export const getCountries = async (_req: Request, res: Response) => {
  const repo = AppDataSource.getRepository(Country);
  const countries = await repo.find();
  res.json(countries);
};

export const updateCountry = async (req: Request, res: Response) => {
  const id = parseInt(req.params.id);
  const repo = AppDataSource.getRepository(Country);
  const country = await repo.findOneBy({ country_id: id });
  if (!country) return res.status(404).json({ message: 'Country not found' });
  Object.assign(country, req.body);
  const updated = await repo.save(country);
  res.json(updated);
};

export const deleteCountry = async (req: Request, res: Response) => {
  const id = parseInt(req.params.id);
  const repo = AppDataSource.getRepository(Country);
  const result = await repo.delete(id);
  result.affected
    ? res.json({ message: 'Country deleted' })
    : res.status(404).json({ message: 'Country not found' });
};