import { pool } from '../db/connection.js';
import logger from '../utils/logger.js';
import { notFound } from '../utils/errors.js';

// ============================================================================
// CREATE Project
// ============================================================================

export const createProject = async (data, ownerId) => {
  const query = `
    INSERT INTO projects (
      name, description, status, color_hex, icon_name, owner_id,
      created_at, updated_at
    )
    VALUES ($1, $2, $3, $4, $5, $6, NOW(), NOW())
    RETURNING id, name, description, status, color_hex, icon_name, 
              owner_id, created_at, updated_at;
  `;
  
  try {
    const result = await pool.query(query, [
      data.name,
      data.description || null,
      'active',
      data.color_hex,
      data.icon_name || null,
      ownerId
    ]);
    
    return result.rows[0];
  } catch (error) {
    logger.error({
      message: 'Error creating project',
      error: error.message,
      data
    });
    throw error;
  }
};

// ============================================================================
// LIST Projects with Stats
// ============================================================================

export const listProjects = async (filter) => {
  const query = `
    SELECT 
      p.id,
      p.name,
      p.description,
      p.status,
      p.color_hex,
      p.icon_name,
      p.owner_id,
      p.created_at,
      p.updated_at,
      COUNT(t.id)::INT AS task_count,
      COALESCE(SUM(CASE WHEN t.status = 'done' THEN 1 ELSE 0 END), 0)::INT AS completed_count,
      COALESCE(SUM(CASE WHEN t.due_date < CURRENT_DATE AND t.status != 'done' THEN 1 ELSE 0 END), 0)::INT AS overdue_count
    FROM projects p
    LEFT JOIN tasks t ON p.id = t.project_id
    WHERE p.status = $1
    GROUP BY p.id
    ORDER BY p.updated_at DESC
    LIMIT $2
    OFFSET $3;
  `;
  
  const countQuery = `
    SELECT COUNT(*)::INT as total
    FROM projects
    WHERE status = $1;
  `;
  
  try {
    const [dataResult, countResult] = await Promise.all([
      pool.query(query, [filter.status, filter.limit, filter.offset]),
      pool.query(countQuery, [filter.status])
    ]);
    
    return {
      projects: dataResult.rows,
      total: countResult.rows[0].total
    };
  } catch (error) {
    logger.error({
      message: 'Error listing projects',
      error: error.message,
      filter
    });
    throw error;
  }
};

// ============================================================================
// GET Project Detail
// ============================================================================

export const getProject = async (projectId) => {
  const query = `
    SELECT 
      id, name, description, status, color_hex, icon_name,
      owner_id, created_at, updated_at
    FROM projects
    WHERE id = $1;
  `;
  
  try {
    const result = await pool.query(query, [projectId]);
    
    if (result.rows.length === 0) {
      notFound('Project');
    }
    
    return result.rows[0];
  } catch (error) {
    if (error.status) throw error;
    
    logger.error({
      message: 'Error fetching project',
      error: error.message,
      projectId
    });
    throw error;
  }
};

// ============================================================================
// UPDATE Project
// ============================================================================

export const updateProject = async (projectId, data) => {
  // Build dynamic update query
  const updates = [];
  const values = [];
  let paramCount = 1;
  
  if (data.name !== undefined) {
    updates.push(`name = $${paramCount++}`);
    values.push(data.name);
  }
  
  if (data.description !== undefined) {
    updates.push(`description = $${paramCount++}`);
    values.push(data.description);
  }
  
  if (data.status !== undefined) {
    updates.push(`status = $${paramCount++}`);
    values.push(data.status);
  }
  
  if (data.color_hex !== undefined) {
    updates.push(`color_hex = $${paramCount++}`);
    values.push(data.color_hex);
  }
  
  if (data.icon_name !== undefined) {
    updates.push(`icon_name = $${paramCount++}`);
    values.push(data.icon_name);
  }
  
  // Always update updated_at
  updates.push(`updated_at = NOW()`);
  
  // Add projectId as last parameter
  values.push(projectId);
  
  const query = `
    UPDATE projects
    SET ${updates.join(', ')}
    WHERE id = $${paramCount}
    RETURNING id, name, description, status, color_hex, icon_name,
              owner_id, created_at, updated_at;
  `;
  
  try {
    const result = await pool.query(query, values);
    
    if (result.rows.length === 0) {
      notFound('Project');
    }
    
    return result.rows[0];
  } catch (error) {
    if (error.status) throw error;
    
    logger.error({
      message: 'Error updating project',
      error: error.message,
      projectId,
      data
    });
    throw error;
  }
};

// ============================================================================
// DELETE Project (cascade deletes tasks)
// ============================================================================

export const deleteProject = async (projectId) => {
  const query = `
    DELETE FROM projects
    WHERE id = $1
    RETURNING id;
  `;
  
  try {
    const result = await pool.query(query, [projectId]);
    
    if (result.rows.length === 0) {
      notFound('Project');
    }
    
    return result.rows[0];
  } catch (error) {
    if (error.status) throw error;
    
    logger.error({
      message: 'Error deleting project',
      error: error.message,
      projectId
    });
    throw error;
  }
};
