import { collection, getDocs, Timestamp } from "firebase/firestore";
import { db } from "../firebase_config";

export type Chantier = {
  id: number;
  adresse: string;
  etat: string;
  contact: string;
  chef: User;
  equipe: User[];
  materiel: Ressources[];
  dateDep: Date;
  tempsEst: number;
  vehicules: Ressources[];
  anomalies: string[];
};

export async function getChantiers(): Promise<Chantier[]> {
  try {
    const colRef = collection(db, "chantier");
    const snapshot = await getDocs(colRef);
    return snapshot.docs.map((doc) => {
      const data = doc.data() as any;
      return {
        ...data,
        chef: {
          ...data.chef,
          allocation: data.chef?.allocation?.map(convertReservation) || [],
        },
        equipe:
          data.equipe?.map((u: any) => ({
            ...u,
            allocation: u.allocation?.map(convertReservation) || [],
          })) || [],
        materiel:
          data.materiel?.map((m: any) => ({
            ...m,
            allocation: m.allocation?.map(convertReservation) || [],
          })) || [],
        vehicules:
          data.vehicules?.map((v: any) => ({
            ...v,
            allocation: v.allocation?.map(convertReservation) || [],
          })) || [],
        anomalies: data.anomalies || [],
      } as Chantier;
    });
  } catch (err) {
    console.error("Firestore Chantiers Error:", err);
    return [];
  }
}

export type User = {
  id: string;
  name: string;
  last_name: string;
  allocation: Reservation[];
  role: string;
  qualifications: string;
};

export async function getUsers(): Promise<User[]> {
  try {
    const colRef = collection(db, "user");
    const snapshot = await getDocs(colRef);
    return snapshot.docs.map((doc) => {
      const data = doc.data();
      return {
        ...data,
        allocation: data.allocation?.map(convertReservation) || [],
      } as User;
    });
  } catch (err) {
    console.error("Firestore Users Error:", err);
    return [];
  }
}

export type Ressources = {
  id: number;
  name: string;
  type: string;
  Image: string;
  quantity: number;
  available_quantity: number;
  allocation: Reservation[];
};

export async function getRessources(): Promise<Ressources[]> {
  try {
    const colRef = collection(db, "ressources");
    const snapshot = await getDocs(colRef);
    return snapshot.docs.map((doc) => {
      const data = doc.data();
      return {
        ...data,
        allocation: data.allocation?.map(convertReservation) || [],
      } as Ressources;
    });
  } catch (err) {
    console.error("Firestore Ressources Error:", err);
    return [];
  }
}

export type Reservation = {
  id: string;
  dateChantier: Date;
  dateFin: Date;
};

function convertReservation(res: any): Reservation {
  return {
    id: res.id,
    dateChantier:
      res.dateChantier instanceof Timestamp
        ? res.dateChantier.toDate()
        : new Date(res.dateChantier),
    dateFin:
      res.dateFin instanceof Timestamp
        ? res.dateFin.toDate()
        : new Date(res.dateFin),
  };
}
