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

export const createCity = async (req: Request, res: Response) => {
  try {
    const { name, state_id } = req.body;
    const state = await AppDataSource.getRepository(State).findOneBy({ state_id });
    if (!state) return res.status(404).json({ message: 'State not found' });
    const city = AppDataSource.getRepository(City).create({ name, state });
    const saved = await AppDataSource.getRepository(City).save(city);
    res.status(201).json(saved);
  } catch (e) {
    res.status(500).json({ message: 'Failed to create city', error: e });
  }
};

export const getCities = async (_req: Request, res: Response) => {
  const cities = await AppDataSource.getRepository(City).find({ relations: ['state'] });
  res.json(cities);
};

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

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