import { Injectable } from '@nestjs/common';
import { DatabaseService } from '../database/database.service';

@Injectable()
export class DocumentsService {
  constructor(private readonly db: DatabaseService) {}

  async expiring(days = 30) {
    const safeDays = Math.max(1, Math.min(365, Number(days) || 30));
    if (!this.db.isConfigured()) return { configured: false, days: safeDays, licenses: [], projectDocuments: [] };
    const [licenses, documents] = await Promise.all([
      this.db.query(
        `SELECT id, project_id, license_type, issuing_authority, expiry_date, status, public_visible
         FROM license_records
         WHERE expiry_date IS NOT NULL AND expiry_date BETWEEN CURRENT_DATE AND CURRENT_DATE + ($1::int * INTERVAL '1 day')
         ORDER BY expiry_date`,
        [safeDays]
      ),
      this.db.query(
        `SELECT id, project_id, name, version, confidentiality, status, expires_at
         FROM project_documents
         WHERE expires_at IS NOT NULL AND expires_at BETWEEN now() AND now() + ($1::int * INTERVAL '1 day')
         ORDER BY expires_at`,
        [safeDays]
      )
    ]);
    return { configured: true, days: safeDays, licenses: licenses.rows, projectDocuments: documents.rows };
  }
}
