import { Request, Response } from "express";
import { AppDataSource } from "../../config/typeOrm"; // Adjust path to your config file
import { Country } from "../../database/entities";
import { State } from "../../database/entities";
import { City } from "../../database/entities";

// Fetch all countries
export const getCountries = async (req: Request, res: Response): Promise<void> => {
  try {
    const countries = await AppDataSource.getRepository(Country).find(
      {
        order: {
          country_name: 'ASC',  
        },
      }
    );
    const countryList = countries.map(country => ({
      id: country.country_id,
      name: country.country_name,
    }));
    res.status(200).json(countryList);
  } catch (error) {
    console.error("Error fetching countries:", error);
    res.status(500).json({ message: "Error fetching countries" });
  }
};

export const getStates = async (req: Request, res: Response): Promise<void> => {
  const {countryid} = req.params;

  // Log the value of countryId for debugging
  console.log('Received countryId:', countryid);

  // Ensure the countryId is a valid number
  const countryIdNumber = +countryid; // Using the unary plus operator to convert to a number

  try {
    const states = await AppDataSource.getRepository(State).find({
      where: { country_id: countryIdNumber },
      order: {
        state_name: 'ASC',  
      },
    });
    const stateList = states.map(state => ({
      id: state.state_id,
      name: state.state_name,
    }));
    res.status(200).json(stateList);
  } catch (error) {
    console.error("Error fetching states:", error);
    res.status(500).json({ message: "Error fetching states" });
  }
};


// Fetch cities by state ID
export const getCities = async (req: Request, res: Response): Promise<void> => {
  const { stateId } = req.params;
  try {
    const cities = await AppDataSource.getRepository(City).find({
      where: { state_id: parseInt(stateId, 10) },
      order: {
        city_name: 'ASC',  
      },
    });
    const cityList = cities.map(city => ({
      id: city.city_id,
      name: city.city_name,
    }));
    res.status(200).json(cityList);
  } catch (error) {
    console.error("Error fetching cities:", error);
    res.status(500).json({ message: "Error fetching cities" });
  }
};
