import { pool } from '../config/database';
import { RowDataPacket, ResultSetHeader } from 'mysql2';

export interface Milestone extends RowDataPacket {
  id: number;
  residence_project_id: number;
  title: string;
  description: string | null;
  completion_percentage: number;
  validation_date: Date | null;
  validated_by: number | null;
  status: 'PENDING' | 'IN_PROGRESS' | 'COMPLETED' | 'VALIDATED';
}

export interface Update extends RowDataPacket {
  id: number;
  residence_project_id: number;
  title: string;
  slug: string;
  content: string | null;
  status: 'DRAFT' | 'PUBLISHED';
  published_at: Date | null;
  author_id: number | null;
}

export interface Photo extends RowDataPacket {
  id: number;
  construction_update_id: number;
  file_url: string;
  caption: string | null;
  sort_order: number;
}

// --- MILESTONES ---

export const findMilestonesByProject = async (projectId: number): Promise<Milestone[]> => {
  const query = `
    SELECT m.*, 
           (SELECT file_url FROM construction_milestone_photos p WHERE p.milestone_id = m.id ORDER BY sort_order ASC, id ASC LIMIT 1) as cover_photo
    FROM construction_milestones m
    WHERE m.residence_project_id = ? 
    ORDER BY m.id ASC
  `;
  const [rows] = await pool.query<Milestone[]>(query, [projectId]);
  return rows;
};

export const findMilestoneById = async (id: number): Promise<Milestone | null> => {
  const [rows] = await pool.query<Milestone[]>('SELECT * FROM construction_milestones WHERE id = ?', [id]);
  return rows[0] || null;
};

export const createMilestone = async (projectId: number, data: any): Promise<number> => {
  const query = `
    INSERT INTO construction_milestones 
    (residence_project_id, title, description, completion_percentage, status, validation_date)
    VALUES (?, ?, ?, ?, ?, ?)
  `;
  const [result] = await pool.query(query, [
    projectId,
    data.title,
    data.description || null,
    data.completion_percentage,
    data.status || 'PENDING',
    data.validation_date || null
  ]);
  return (result as ResultSetHeader).insertId;
};

export const updateMilestone = async (id: number, data: any): Promise<void> => {
  const query = `
    UPDATE construction_milestones 
    SET title = COALESCE(?, title),
        description = COALESCE(?, description),
        completion_percentage = COALESCE(?, completion_percentage),
        status = COALESCE(?, status),
        validation_date = COALESCE(?, validation_date),
        validated_by = COALESCE(?, validated_by)
    WHERE id = ?
  `;
  await pool.query(query, [
    data.title !== undefined ? data.title : null,
    data.description !== undefined ? data.description : null,
    data.completion_percentage !== undefined ? data.completion_percentage : null,
    data.status !== undefined ? data.status : null,
    data.validation_date !== undefined ? data.validation_date : null,
    data.validated_by !== undefined ? data.validated_by : null,
    id
  ]);
};

export const removeMilestone = async (id: number): Promise<void> => {
  await pool.query('DELETE FROM construction_milestones WHERE id = ?', [id]);
};

// --- MILESTONE PHOTOS ---

export const findPhotosByMilestone = async (milestoneId: number): Promise<any[]> => {
  const [rows] = await pool.query<any[]>(
    'SELECT * FROM construction_milestone_photos WHERE milestone_id = ? ORDER BY sort_order ASC, id ASC',
    [milestoneId]
  );
  return rows;
};

export const addMilestonePhoto = async (milestoneId: number, fileUrl: string, caption?: string): Promise<number> => {
  const [result] = await pool.query(
    'INSERT INTO construction_milestone_photos (milestone_id, file_url, caption) VALUES (?, ?, ?)',
    [milestoneId, fileUrl, caption || null]
  );
  return (result as ResultSetHeader).insertId;
};

export const deleteMilestonePhoto = async (id: number): Promise<void> => {
  await pool.query('DELETE FROM construction_milestone_photos WHERE id = ?', [id]);
};

// --- UPDATES (ACTUALITÉS) ---

export const findUpdatesByProject = async (projectId: number, onlyPublished = false): Promise<Update[]> => {
  let query = `
    SELECT u.*, 
           (SELECT file_url FROM construction_photos p WHERE p.construction_update_id = u.id ORDER BY sort_order ASC, id ASC LIMIT 1) as cover_photo
    FROM construction_updates u
    WHERE u.residence_project_id = ?
  `;
  if (onlyPublished) query += ' AND u.status = "PUBLISHED"';
  query += ' ORDER BY u.published_at DESC, u.created_at DESC';
  
  const [rows] = await pool.query<Update[]>(query, [projectId]);
  return rows;
};

export const findUpdateById = async (id: number): Promise<Update | null> => {
  const [rows] = await pool.query<Update[]>('SELECT * FROM construction_updates WHERE id = ?', [id]);
  return rows[0] || null;
};

export const findUpdateBySlug = async (slug: string): Promise<Update | null> => {
  const [rows] = await pool.query<Update[]>('SELECT * FROM construction_updates WHERE slug = ?', [slug]);
  return rows[0] || null;
};

export const createUpdate = async (projectId: number, data: any): Promise<number> => {
  const query = `
    INSERT INTO construction_updates 
    (residence_project_id, title, slug, content, status, published_at, created_by)
    VALUES (?, ?, ?, ?, ?, ?, ?)
  `;
  const [result] = await pool.query(query, [
    projectId,
    data.title,
    data.slug,
    data.content || null,
    data.status || 'DRAFT',
    data.status === 'PUBLISHED' ? new Date() : null,
    data.author_id
  ]);
  return (result as ResultSetHeader).insertId;
};

export const updateUpdate = async (id: number, data: any): Promise<void> => {
  const query = `
    UPDATE construction_updates 
    SET title = COALESCE(?, title),
        slug = COALESCE(?, slug),
        content = COALESCE(?, content),
        status = COALESCE(?, status),
        published_at = COALESCE(?, published_at)
    WHERE id = ?
  `;
  await pool.query(query, [
    data.title !== undefined ? data.title : null,
    data.slug !== undefined ? data.slug : null,
    data.content !== undefined ? data.content : null,
    data.status !== undefined ? data.status : null,
    data.published_at !== undefined ? data.published_at : null,
    id
  ]);
};

export const removeUpdate = async (id: number): Promise<void> => {
  await pool.query('DELETE FROM construction_updates WHERE id = ?', [id]);
};

// --- PHOTOS ---

export const findPhotosByUpdate = async (updateId: number): Promise<Photo[]> => {
  const [rows] = await pool.query<Photo[]>('SELECT * FROM construction_photos WHERE construction_update_id = ? ORDER BY sort_order ASC', [updateId]);
  return rows;
};

export const findPhotoById = async (id: number): Promise<Photo | null> => {
  const [rows] = await pool.query<Photo[]>('SELECT * FROM construction_photos WHERE id = ?', [id]);
  return rows[0] || null;
};

export const createPhoto = async (updateId: number, data: any): Promise<number> => {
  const query = `
    INSERT INTO construction_photos 
    (construction_update_id, file_url, caption, sort_order)
    VALUES (?, ?, ?, ?)
  `;
  const [result] = await pool.query(query, [
    updateId,
    data.file_url,
    data.caption || null,
    data.sort_order || 0
  ]);
  return (result as ResultSetHeader).insertId;
};

export const removePhoto = async (id: number): Promise<void> => {
  await pool.query('DELETE FROM construction_photos WHERE id = ?', [id]);
};
