const { getPool } = require('./partnerModel');

async function findBySchedule(scheduleId) {
  const db = getPool();
  const [rows] = await db.query(
    `SELECT pc.*, pco.company_name, su.name AS checked_by_name
     FROM partner_work_checkins pc
     LEFT JOIN partner_companies pco ON pc.company_id = pco.id
     LEFT JOIN sso_users su ON pc.checked_by = su.user_id
     WHERE pc.schedule_id = ?
     ORDER BY pc.check_in_time DESC`, [scheduleId]);
  return rows;
}

async function findById(id) {
  const db = getPool();
  const [rows] = await db.query(
    `SELECT pc.*, pco.company_name, su.name AS checked_by_name
     FROM partner_work_checkins pc
     LEFT JOIN partner_companies pco ON pc.company_id = pco.id
     LEFT JOIN sso_users su ON pc.checked_by = su.user_id
     WHERE pc.id = ?`, [id]);
  return rows[0] || null;
}

async function findTodayByCompany(companyId) {
  const db = getPool();
  const [rows] = await db.query(
    `SELECT pc.*, ps.work_description, ps.workplace_name,
            (SELECT COUNT(*) FROM partner_work_reports WHERE checkin_id = pc.id) AS work_report_count
     FROM partner_work_checkins pc
     LEFT JOIN partner_schedules ps ON pc.schedule_id = ps.id
     WHERE pc.company_id = ? AND DATE(pc.check_in_time) = CURDATE()
     ORDER BY pc.check_in_time DESC`, [companyId]);
  return rows;
}

async function checkIn(data) {
  const db = getPool();
  const [result] = await db.query(
    `INSERT INTO partner_work_checkins (schedule_id, company_id, checked_by, check_in_time, worker_names, actual_worker_count, notes)
     VALUES (?, ?, ?, NOW(), ?, ?, ?)`,
    [data.schedule_id, data.company_id, data.checked_by,
     data.worker_names ? JSON.stringify(data.worker_names) : null,
     data.actual_worker_count || null, data.notes || null]);
  return findById(result.insertId);
}

async function checkOut(id) {
  const db = getPool();
  await db.query('UPDATE partner_work_checkins SET check_out_time = NOW() WHERE id = ? AND check_out_time IS NULL', [id]);
  return findById(id);
}

async function update(id, data) {
  const db = getPool();
  const fields = [];
  const values = [];
  if (data.worker_names !== undefined) { fields.push('worker_names = ?'); values.push(data.worker_names ? JSON.stringify(data.worker_names) : null); }
  if (data.actual_worker_count !== undefined) { fields.push('actual_worker_count = ?'); values.push(data.actual_worker_count || null); }
  if (data.notes !== undefined) { fields.push('notes = ?'); values.push(data.notes || null); }
  if (fields.length === 0) return findById(id);
  values.push(id);
  await db.query(`UPDATE partner_work_checkins SET ${fields.join(', ')} WHERE id = ?`, values);
  return findById(id);
}

async function resetCheckout(id) {
  const db = getPool();
  await db.query('UPDATE partner_work_checkins SET check_out_time = NULL WHERE id = ?', [id]);
}

async function countActive() {
  const db = getPool();
  const [rows] = await db.query(
    `SELECT COUNT(*) AS cnt FROM partner_work_checkins
     WHERE check_out_time IS NULL AND DATE(check_in_time) = CURDATE()`);
  return rows[0].cnt;
}

async function deleteCheckin(id) {
  const checkin = await findById(id);
  if (!checkin) return false;

  const db = getPool();
  const conn = await db.getConnection();
  try {
    await conn.beginTransaction();
    await conn.query('DELETE FROM partner_work_reports WHERE checkin_id = ?', [id]);
    await conn.query('DELETE FROM partner_work_checkins WHERE id = ?', [id]);
    const [remaining] = await conn.query(
      'SELECT COUNT(*) AS cnt FROM partner_work_checkins WHERE schedule_id = ?',
      [checkin.schedule_id]);
    if (remaining[0].cnt === 0) {
      await conn.query(
        "UPDATE partner_schedules SET status = 'scheduled' WHERE id = ? AND status = 'in_progress'",
        [checkin.schedule_id]);
    }
    await conn.commit();
    return true;
  } catch (err) {
    await conn.rollback();
    throw err;
  } finally {
    conn.release();
  }
}

async function checkOutWithReport(id, reportData) {
  const db = getPool();
  const checkin = await findById(id);
  if (!checkin) throw new Error('체크인 기록을 찾을 수 없습니다');
  if (checkin.check_out_time) throw new Error('이미 체크아웃된 기록입니다');

  const conn = await db.getConnection();
  try {
    await conn.beginTransaction();

    // report_seq: 같은 checkin_id 내 최대값 + 1
    const [seqRows] = await conn.query(
      'SELECT COALESCE(MAX(report_seq), 0) + 1 AS next_seq FROM partner_work_reports WHERE checkin_id = ?',
      [id]);
    const reportSeq = seqRows[0].next_seq;

    const workers = reportData.workers || [];

    const [reportResult] = await conn.query(
      `INSERT INTO partner_work_reports (schedule_id, checkin_id, company_id, report_date, report_seq, reporter_id, actual_workers, work_content, progress_rate)
       VALUES (?, ?, ?, CURDATE(), ?, ?, ?, ?, ?)`,
      [checkin.schedule_id, id, checkin.company_id, reportSeq,
       reportData.reporter_id, workers.length,
       reportData.work_content || '작업 완료', 100]);

    const reportId = reportResult.insertId;

    // workers 삽입
    for (const w of workers) {
      await conn.query(
        `INSERT INTO work_report_workers (report_id, partner_worker_id, worker_name, hours_worked)
         VALUES (?, ?, ?, ?)`,
        [reportId, w.partner_worker_id || null, w.worker_name, w.hours_worked ?? 8.0]);
    }

    // 체크아웃
    await conn.query('UPDATE partner_work_checkins SET check_out_time = NOW() WHERE id = ?', [id]);

    await conn.commit();
    return findById(id);
  } catch (err) {
    await conn.rollback();
    throw err;
  } finally {
    conn.release();
  }
}

async function findHistoryByCompany(companyId, { dateFrom, dateTo, page = 1, limit = 20 } = {}) {
  const db = getPool();

  // 1. 체크인 페이지네이션 조회
  let sql = `SELECT pc.*, ps.work_description, ps.workplace_name, ps.start_date, ps.end_date, p.project_name, p.job_no
     FROM partner_work_checkins pc
     LEFT JOIN partner_schedules ps ON pc.schedule_id = ps.id
     LEFT JOIN projects p ON ps.project_id = p.project_id
     WHERE pc.company_id = ?`;
  const params = [companyId];
  if (dateFrom) { sql += ' AND DATE(pc.check_in_time) >= ?'; params.push(dateFrom); }
  if (dateTo) { sql += ' AND DATE(pc.check_in_time) <= ?'; params.push(dateTo); }
  sql += ' ORDER BY pc.check_in_time DESC';

  // count
  const countSql = sql.replace(/SELECT pc\.\*.*?FROM/, 'SELECT COUNT(*) AS total FROM');
  const [countRows] = await db.query(countSql, params);
  const total = countRows[0].total;

  const offset = (page - 1) * limit;
  sql += ' LIMIT ? OFFSET ?';
  params.push(limit, offset);
  const [checkins] = await db.query(sql, params);

  if (checkins.length === 0) return { data: [], total, page, limit };

  // 2. 해당 체크인들의 reports 일괄 조회
  const checkinIds = checkins.map(c => c.id);
  const [reports] = await db.query(
    `SELECT * FROM partner_work_reports WHERE checkin_id IN (?) ORDER BY report_seq ASC`,
    [checkinIds]);

  // 3. 해당 reports의 workers 일괄 조회
  const reportIds = reports.map(r => r.id);
  let workers = [];
  if (reportIds.length > 0) {
    const [workerRows] = await db.query(
      `SELECT * FROM work_report_workers WHERE report_id IN (?) ORDER BY id`,
      [reportIds]);
    workers = workerRows;
  }

  // 조립
  const workersByReport = {};
  workers.forEach(w => {
    if (!workersByReport[w.report_id]) workersByReport[w.report_id] = [];
    workersByReport[w.report_id].push(w);
  });

  const reportsByCheckin = {};
  reports.forEach(r => {
    r.workers = workersByReport[r.id] || [];
    if (!reportsByCheckin[r.checkin_id]) reportsByCheckin[r.checkin_id] = [];
    reportsByCheckin[r.checkin_id].push(r);
  });

  checkins.forEach(c => {
    c.reports = reportsByCheckin[c.id] || [];
  });

  return { data: checkins, total, page, limit };
}

async function findActiveByCompany(companyId) {
  const db = getPool();
  const [rows] = await db.query(
    `SELECT pc.*, ps.work_description, ps.workplace_name,
            (SELECT COUNT(*) FROM partner_work_reports WHERE checkin_id = pc.id) AS work_report_count
     FROM partner_work_checkins pc
     LEFT JOIN partner_schedules ps ON pc.schedule_id = ps.id
     WHERE pc.company_id = ?
       AND (pc.check_out_time IS NULL OR DATE(pc.check_in_time) = CURDATE())
     ORDER BY pc.check_in_time DESC`, [companyId]);
  return rows;
}

module.exports = { findBySchedule, findById, findTodayByCompany, findActiveByCompany, checkIn, checkOut, update, resetCheckout, countActive, deleteCheckin, checkOutWithReport, findHistoryByCompany };
