import { Request, Response } from 'express';
import environment from '../config/environment';
import settingsService from '../services/settings.service';

class ConfigController {
  async getServiceMode(_req: Request, res: Response): Promise<void> {
    try {
      const setting = await settingsService.get('service_mode');
      const value = setting?.value ?? { active: false, message: '' };
      res.json({ success: true, data: value });
    } catch {
      res.json({ success: true, data: { active: false, message: '' } });
    }
  }

  async getPdfSettings(_req: Request, res: Response): Promise<void> {
    try {
      const [header, footer, logo, orgName, appLogo] = await Promise.all([
        settingsService.get('pdf_header'),
        settingsService.get('pdf_footer'),
        settingsService.get('pdf_logo'),
        settingsService.get('pdf_org_name'),
        settingsService.get('app_logo'),
      ]);
      res.json({
        success: true,
        data: {
          pdf_header: header?.value ?? '',
          pdf_footer: footer?.value ?? '',
          pdf_logo: logo?.value ?? '',
          pdf_org_name: orgName?.value ?? '',
          app_logo: appLogo?.value ?? '',
        },
      });
    } catch {
      res.json({ success: true, data: { pdf_header: '', pdf_footer: '', pdf_logo: '', pdf_org_name: '', app_logo: '' } });
    }
  }

  async getExternalLinks(_req: Request, res: Response): Promise<void> {
    const envLinks: Record<string, string> = {};
    if (environment.nextcloudUrl) envLinks.nextcloud = environment.nextcloudUrl;
    if (environment.bookstack.url) envLinks.bookstack = environment.bookstack.url;
    if (environment.vikunja.url) envLinks.vikunja = environment.vikunja.url;

    const linkCollections = await settingsService.getExternalLinks();

    res.status(200).json({
      success: true,
      data: {
        ...envLinks,
        customLinks: linkCollections.flatMap(c => c.links),
        linkCollections,
      },
    });
  }
}

export default new ConfigController();
