import { getDb } from '../database/database';
import { localTimestamp, formatLocalDate } from '../utils/time';
import { CloudConfig, getCloudConfigById } from './credential.service';

export async function dailyCheckIn(id: number): Promise<{
  success: boolean;
  message: string;
  signedDays?: number;
}> {
  const db = getDb();
  const config = db.prepare(
    'SELECT * FROM cloud_configs WHERE id = ?'
  ).get(id) as CloudConfig | undefined;
  if (!config || !config.cookie) {
    return { success: false, message: '未找到该网盘的有效配置' };
  }
  try {
    const { QuarkDriver } = require('./drivers/quark.driver');
    const driver = new QuarkDriver({ cookie: config.cookie });
    const result = await driver.checkIn();

    if (result.success) {
      db.prepare(
        `UPDATE cloud_configs SET
         checkin_status = 'success',
         last_checkin_at = datetime('now','localtime'),
         checkin_message = ?,
         consecutive_failures = 0
         WHERE id = ?`
      ).run(result.message || '签到成功', id);
    } else {
      db.prepare(
        `UPDATE cloud_configs SET
         checkin_status = 'failed',
         last_checkin_at = datetime('now','localtime'),
         checkin_message = ?,
         consecutive_failures = consecutive_failures + 1
         WHERE id = ?`
      ).run(result.message || '签到失败', id);
    }

    try {
      const storage = await driver.getStorageInfo();
      db.prepare(
        `UPDATE cloud_configs SET storage_used = ?, storage_total = ? WHERE id = ?`
      ).run(storage.used, storage.total, id);
    } catch {
      // Storage info fetch is best-effort
    }

    return result;
  } catch (err: any) {
    db.prepare(
      `UPDATE cloud_configs SET
       checkin_status = 'failed',
       last_checkin_at = datetime('now','localtime'),
       checkin_message = ?,
       consecutive_failures = consecutive_failures + 1
       WHERE id = ?`
    ).run(err.message || '签到失败：未知错误', id);

    return { success: false, message: `签到失败：${err.message || '未知错误'}` };
  }
}

/** Get all quark drives that need checkin today. */
export function getDrivesForCheckin(): CloudConfig[] {
  const db = getDb();
  return db.prepare(
    `SELECT * FROM cloud_configs
     WHERE cloud_type = 'quark' AND is_active = 1
     AND (checkin_status IS NULL OR checkin_status != 'success'
          OR last_checkin_at IS NULL
          OR last_checkin_at < date('now','localtime'))`
  ).all() as CloudConfig[];
}

/** Skip checkin for a drive. */
export function skipCheckin(id: number): boolean {
  const db = getDb();
  const result = db.prepare(
    `UPDATE cloud_configs SET
     checkin_status = 'skipped',
     last_checkin_at = datetime('now','localtime'),
     checkin_message = '已跳过签到'
     WHERE id = ?`
  ).run(id);
  return result.changes > 0;
}

/** Get today's checkin summary for quark drives. */
export function getCheckinSummary(): {
  total: number;
  success: number;
  failed: number;
  pending: number;
  skipped: number;
} {
  const db = getDb();
  const todayStr = formatLocalDate();

  const all = db.prepare(
    `SELECT checkin_status, COUNT(*) as count FROM cloud_configs
     WHERE cloud_type = 'quark' AND is_active = 1
     GROUP BY checkin_status`
  ).all() as { checkin_status: string; count: number }[];

  const neverCheckedInToday = db.prepare(
    `SELECT COUNT(*) as count FROM cloud_configs
     WHERE cloud_type = 'quark' AND is_active = 1
     AND (last_checkin_at IS NULL OR last_checkin_at < ?)`
  ).get(todayStr) as { count: number };

  const summary: Record<string, number> = {
    success: 0,
    failed: 0,
    pending: 0,
    skipped: 0,
  };

  for (const row of all) {
    if (row.checkin_status === 'none' || row.checkin_status === null) {
      summary.pending += row.count;
    } else if (row.checkin_status in summary) {
      summary[row.checkin_status] += row.count;
    }
  }

  summary.pending += neverCheckedInToday.count;

  const total = Object.values(summary).reduce((a, b) => a + b, 0);

  return {
    total,
    success: summary.success,
    failed: summary.failed,
    pending: summary.pending,
    skipped: summary.skipped,
  };
}
