import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { createRequire } from 'node:module';

// Загружаем .env из корня монорепо (apps/frontend -> корень)
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const rootDir = path.resolve(__dirname, '..', '..');
const require = createRequire(import.meta.url);
require('dotenv').config({ path: path.join(rootDir, '.env') });

import pkg from './package.json' with { type: 'json' };

/** @type {import('next').NextConfig} */
const nextConfig = {
  output: 'standalone',
  images: {
    remotePatterns: [
      { hostname: 's2.googleusercontent.com' },
      { hostname: 'images.unsplash.com' },
      { hostname: 'placehold.co' },
    ],
  },
  serverExternalPackages: ['pdf-parse'],
  outputFileTracingIncludes: {
    '/api/**': [
      './node_modules/@napi-rs/canvas/**',
      './node_modules/@napi-rs/canvas-linux-x64-gnu/**',
      './node_modules/@napi-rs/canvas-linux-x64-musl/**',
    ],
  },
  env: {
    NEXT_PUBLIC_VERSION: pkg.version,
  },
  async rewrites() {
    const gateway = process.env.API_GATEWAY_URL ?? 'http://localhost:3015';
    return [
      { source: '/api/chat', destination: `${gateway}/api/chat` },
      { source: '/api/v1/:path*', destination: `${gateway}/api/v1/:path*` },
      { source: '/api/config', destination: `${gateway}/api/v1/config` },
      { source: '/api/config/:path*', destination: `${gateway}/api/v1/config/:path*` },
      { source: '/api/providers', destination: `${gateway}/api/v1/providers` },
      { source: '/api/providers/:path*', destination: `${gateway}/api/v1/providers/:path*` },
      { source: '/api/weather', destination: `${gateway}/api/v1/weather` },
      { source: '/api/auth/:path*', destination: `${gateway}/api/auth/:path*` },
      { source: '/api/locale', destination: `${gateway}/api/locale` },
      { source: '/api/translations/:path*', destination: `${gateway}/api/translations/:path*` },
      { source: '/api/geo-context', destination: `${gateway}/api/geo-context` },
      { source: '/api/images', destination: `${gateway}/api/images` },
      { source: '/api/videos', destination: `${gateway}/api/videos` },
      { source: '/api/suggestions', destination: `${gateway}/api/suggestions` },
    ];
  },
};

const withPWA = require('@ducanh2912/next-pwa').default({
  dest: 'public',
  disable: process.env.NODE_ENV === 'development',
  register: true,
  skipWaiting: true,
  fallbacks: {
    document: '/offline',
  },
});

export default withPWA(nextConfig);
