/* eslint-disable @typescript-eslint/no-explicit-any */
import multer from 'multer';
import path from 'path';
import fs from 'fs';
import logger from '../utils/logger';

// In Docker the working dir is /app and the volume is mounted at /app/uploads.
// In dev, resolve relative to the project root (3 levels up from dist/middleware/).
const APP_ROOT = process.env.NODE_ENV === 'production' ? '/app' : path.resolve(__dirname, '../../..');
const UPLOAD_DIR = path.join(APP_ROOT, 'uploads', 'bestellungen');
const THUMBNAIL_DIR = path.join(APP_ROOT, 'uploads', 'bestellungen', 'thumbnails');

// Ensure directories exist (graceful — may already exist via Docker volume)
[UPLOAD_DIR, THUMBNAIL_DIR].forEach(dir => {
  try {
    if (!fs.existsSync(dir)) {
      fs.mkdirSync(dir, { recursive: true });
      logger.info(`Created upload directory: ${dir}`);
    }
  } catch (err) {
    logger.warn(`Could not create upload directory ${dir} — it may be created by Docker volume mount`, { err });
  }
});

const storage = multer.diskStorage({
  destination(_req: any, _file: any, cb: any) {
    cb(null, UPLOAD_DIR);
  },
  filename(_req: any, file: any, cb: any) {
    const uniqueSuffix = `${Date.now()}-${Math.round(Math.random() * 1e9)}`;
    const ext = path.extname(file.originalname);
    cb(null, `${uniqueSuffix}${ext}`);
  },
});

const ALLOWED_TYPES = [
  'image/jpeg', 'image/png', 'image/gif', 'image/webp',
  'application/pdf',
  'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  'text/plain', 'text/csv',
];

const multerOptions: any = {
  storage,
  fileFilter(_req: any, file: any, cb: any) {
    if (ALLOWED_TYPES.includes(file.mimetype)) {
      cb(null, true);
    } else {
      cb(new Error(`Dateityp ${file.mimetype} ist nicht erlaubt.`));
    }
  },
  limits: { fileSize: 20 * 1024 * 1024 }, // 20 MB
};

// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const uploadBestellung: any = multer(multerOptions);

// ── Wartungslog uploads (vehicle/equipment service reports) ──────────────────

const WARTUNG_DIR = path.join(APP_ROOT, 'uploads', 'wartung');
try {
  if (!fs.existsSync(WARTUNG_DIR)) {
    fs.mkdirSync(WARTUNG_DIR, { recursive: true });
  }
} catch (err) {
  logger.warn(`Could not create wartung upload directory`, { err });
}

const wartungStorage = multer.diskStorage({
  destination(_req: any, _file: any, cb: any) {
    cb(null, WARTUNG_DIR);
  },
  filename(_req: any, file: any, cb: any) {
    const uniqueSuffix = `${Date.now()}-${Math.round(Math.random() * 1e9)}`;
    const ext = path.extname(file.originalname);
    cb(null, `${uniqueSuffix}${ext}`);
  },
});

// eslint-disable-next-line @typescript-eslint/no-explicit-any
const wartungOptions: any = {
  storage: wartungStorage,
  fileFilter(_req: any, file: any, cb: any) {
    if (ALLOWED_TYPES.includes(file.mimetype)) {
      cb(null, true);
    } else {
      cb(new Error(`Dateityp ${file.mimetype} ist nicht erlaubt.`));
    }
  },
  limits: { fileSize: 20 * 1024 * 1024 },
};

// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const uploadWartung: any = multer(wartungOptions);

// ── Issue uploads ────────────────────────────────────────────────────────────

const ISSUE_DIR = path.join(APP_ROOT, 'uploads', 'issues');
try {
  if (!fs.existsSync(ISSUE_DIR)) {
    fs.mkdirSync(ISSUE_DIR, { recursive: true });
  }
} catch (err) {
  logger.warn(`Could not create issue upload directory`, { err });
}

const issueStorage = multer.diskStorage({
  destination(_req: any, _file: any, cb: any) {
    cb(null, ISSUE_DIR);
  },
  filename(_req: any, file: any, cb: any) {
    const uniqueSuffix = `${Date.now()}-${Math.round(Math.random() * 1e9)}`;
    const ext = path.extname(file.originalname);
    cb(null, `${uniqueSuffix}${ext}`);
  },
});

// eslint-disable-next-line @typescript-eslint/no-explicit-any
const issueOptions: any = {
  storage: issueStorage,
  fileFilter(_req: any, file: any, cb: any) {
    if (ALLOWED_TYPES.includes(file.mimetype)) {
      cb(null, true);
    } else {
      cb(new Error(`Dateityp ${file.mimetype} ist nicht erlaubt.`));
    }
  },
  limits: { fileSize: 20 * 1024 * 1024 },
};

// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const uploadIssue: any = multer(issueOptions);

// ── Buchhaltung uploads (accounting receipts / Belege) ───────────────────────

const BUCHHALTUNG_DIR = path.join(APP_ROOT, 'uploads', 'buchhaltung');
try {
  if (!fs.existsSync(BUCHHALTUNG_DIR)) {
    fs.mkdirSync(BUCHHALTUNG_DIR, { recursive: true });
  }
} catch (err) {
  logger.warn(`Could not create buchhaltung upload directory`, { err });
}

const buchhaltungStorage = multer.diskStorage({
  destination(_req: any, _file: any, cb: any) {
    cb(null, BUCHHALTUNG_DIR);
  },
  filename(_req: any, file: any, cb: any) {
    const uniqueSuffix = `${Date.now()}-${Math.round(Math.random() * 1e9)}`;
    const ext = path.extname(file.originalname);
    cb(null, `${uniqueSuffix}${ext}`);
  },
});

// eslint-disable-next-line @typescript-eslint/no-explicit-any
const buchhaltungOptions: any = {
  storage: buchhaltungStorage,
  fileFilter(_req: any, file: any, cb: any) {
    if (ALLOWED_TYPES.includes(file.mimetype)) {
      cb(null, true);
    } else {
      cb(new Error(`Dateityp ${file.mimetype} ist nicht erlaubt.`));
    }
  },
  limits: { fileSize: 20 * 1024 * 1024 },
};

// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const uploadBuchhaltung: any = multer(buchhaltungOptions);

export { UPLOAD_DIR, THUMBNAIL_DIR, WARTUNG_DIR, ISSUE_DIR, BUCHHALTUNG_DIR };
