import fs from "fs";
import path from "path";
import { Car } from "./data";

const dataFilePath = path.join(process.cwd(), "data", "cars.json");
const authFilePath = path.join(process.cwd(), "data", "auth.json");

export function getPassword(): string {
  try {
    const fileContents = fs.readFileSync(authFilePath, "utf8");
    const data = JSON.parse(fileContents);
    return data.password || "12345678";
  } catch (error) {
    return "12345678";
  }
}

export function setPassword(newPassword: string): void {
  try {
    fs.writeFileSync(authFilePath, JSON.stringify({ password: newPassword }, null, 2), "utf8");
  } catch (error) {
    console.error("Error writing to auth.json:", error);
  }
}

export function getCars(): Car[] {
  try {
    const fileContents = fs.readFileSync(dataFilePath, "utf8");
    return JSON.parse(fileContents);
  } catch (error) {
    console.error("Error reading cars.json:", error);
    return [];
  }
}

export function saveCars(cars: Car[]): void {
  try {
    fs.writeFileSync(dataFilePath, JSON.stringify(cars, null, 2), "utf8");
  } catch (error) {
    console.error("Error writing to cars.json:", error);
  }
}

export function getCarById(id: string): Car | undefined {
  const cars = getCars();
  return cars.find((c) => c.id === id);
}

export function addCar(car: Car): void {
  const cars = getCars();
  cars.push(car);
  saveCars(cars);
}

export function updateCar(id: string, updatedFields: Partial<Car>): void {
  const cars = getCars();
  const index = cars.findIndex((c) => c.id === id);
  if (index !== -1) {
    cars[index] = { ...cars[index], ...updatedFields };
    saveCars(cars);
  }
}

export function deleteCar(id: string): void {
  let cars = getCars();
  cars = cars.filter((c) => c.id !== id);
  saveCars(cars);
}
