import express = require('express');
import type { Request, Response } from 'express';
const axios = require('axios');
const { authMiddleware } = require('../middleware/auth');
const db = require('../db/database');
const logger = require('../utils/logger');
const cryptoUtil = require('../utils/crypto');
const { serverError } = require('../utils/errors');

const router = express.Router();

router.post('/nextcloud/connect', authMiddleware, async function (req: Request, res: Response) {
  try {
    const { nextcloudUrl, username, appPassword, folder } = req.body;
    if (!nextcloudUrl || !username || !appPassword) return res.status(400).json({ error: 'All fields required' });

    const cleanUrl: string = nextcloudUrl.replace(/\/+$/, '');
    const targetFolder: string = (folder || '/PediatricScribe').replace(/\/+$/, '');

    try {
      await axios({ method: 'PROPFIND', url: cleanUrl + '/remote.php/dav/files/' + username + '/', auth: { username, password: appPassword }, headers: { Depth: '0' } });
    } catch (e) {
      return res.status(400).json({ error: 'Cannot connect. Check credentials.' });
    }

    const parts = targetFolder.split('/').filter(Boolean);
    let current = '';
    for (let i = 0; i < parts.length; i++) {
      current += '/' + parts[i];
      try { await axios({ method: 'MKCOL', url: cleanUrl + '/remote.php/dav/files/' + username + current + '/', auth: { username, password: appPassword } }); } catch (e) {}
    }

    await db.run('UPDATE users SET nextcloud_url = ?, nextcloud_user = ?, nextcloud_token = ?, nextcloud_folder = ? WHERE id = ?',
      [cleanUrl, username, cryptoUtil.encryptString(appPassword), targetFolder, req.user!.id]);

    res.json({ success: true, message: 'Connected! Files saved to ' + targetFolder + '/' });
    logger.audit(req.user!.id, 'nextcloud_connect', 'Connected Nextcloud', req, { category: 'integration' });
  } catch (err) { return serverError(res, 'Nextcloud connect', err, 'Could not connect to Nextcloud'); }
});

router.post('/nextcloud/export', authMiddleware, async function (req: Request, res: Response) {
  try {
    const { content, filename, type } = req.body;
    const user = await db.get('SELECT nextcloud_url, nextcloud_user, nextcloud_token, nextcloud_folder FROM users WHERE id = ?', [req.user!.id]);
    if (!user || !user.nextcloud_url) return res.status(400).json({ error: 'Nextcloud not connected. Go to Settings.' });

    const baseFolder = user.nextcloud_folder || '/PediatricScribe';
    const today = new Date().toISOString().split('T')[0];
    const targetPath = baseFolder + '/' + today;

    let pw: string;
    try { pw = cryptoUtil.decryptString(user.nextcloud_token); }
    catch (decErr) { return res.status(400).json({ error: 'Nextcloud credentials invalid. Please reconnect.' }); }

    const parts = targetPath.split('/').filter(Boolean);
    let current = '';
    for (let i = 0; i < parts.length; i++) {
      current += '/' + parts[i];
      try { await axios({ method: 'MKCOL', url: user.nextcloud_url + '/remote.php/dav/files/' + user.nextcloud_user + current + '/', auth: { username: user.nextcloud_user, password: pw } }); } catch (e) {}
    }

    const time = new Date().toTimeString().split(' ')[0].replace(/:/g, '-');
    const safeName = (filename || type + '-' + time).replace(/[^a-zA-Z0-9-_]/g, '_');
    const filePath = user.nextcloud_url + '/remote.php/dav/files/' + user.nextcloud_user + targetPath + '/' + safeName + '.txt';

    await axios({ method: 'PUT', url: filePath, data: content, auth: { username: user.nextcloud_user, password: pw }, headers: { 'Content-Type': 'text/plain; charset=utf-8' } });

    if (!cryptoUtil.isEncrypted(user.nextcloud_token)) {
      db.run('UPDATE users SET nextcloud_token = ? WHERE id = ?', [cryptoUtil.encryptString(pw), req.user!.id]).catch(() => {});
    }

    res.json({ success: true, message: 'Saved to ' + targetPath + '/' + safeName + '.txt' });
    logger.audit(req.user!.id, 'nextcloud_export', 'Exported note to Nextcloud', req, { category: 'export' });
  } catch (err) { return serverError(res, 'Nextcloud export', err, 'Could not export to Nextcloud'); }
});

router.post('/nextcloud/disconnect', authMiddleware, async function (req: Request, res: Response) {
  try {
    await db.run('UPDATE users SET nextcloud_url = NULL, nextcloud_user = NULL, nextcloud_token = NULL, nextcloud_folder = NULL WHERE id = ?', [req.user!.id]);
    res.json({ success: true });
    logger.audit(req.user!.id, 'nextcloud_disconnect', 'Disconnected Nextcloud', req, { category: 'integration' });
  } catch (err) { return serverError(res, 'Nextcloud disconnect', err, 'Could not disconnect'); }
});

export = router;
