import { config } from 'dotenv';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
config({ path: path.resolve(fileURLToPath(import.meta.url), '../../../../.env') });

/**
 * auth-svc — SSO, JWT, Bearer validation для API-to-API
 * docs/architecture: 01-perplexity-analogue-design.md §3.2, auth-svc
 * Миграция из apps/auth-mcs в services/
 */

import express from 'express';
import cors from 'cors';
import { toNodeHandler, fromNodeHeaders } from 'better-auth/node';
import { auth } from './lib/auth.js';

const PORT = parseInt(process.env.PORT ?? '3014', 10);

const app = express();

app.use(
  cors({
    origin: true,
    methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH'],
    credentials: true,
  })
);

app.get('/api/auth/me', async (req, res) => {
  try {
    const session = await auth.api.getSession({
      headers: fromNodeHeaders(req.headers),
    });
    if (!session?.user?.id) {
      return res.status(401).json({ error: 'Unauthorized' });
    }
    const { id, name, email, image } = session.user;
    return res.json({ id, name: name ?? undefined, email: email ?? undefined, image: image ?? undefined });
  } catch {
    return res.status(401).json({ error: 'Unauthorized' });
  }
});

app.all('/api/auth/*', toNodeHandler(auth));

app.use(express.json({ limit: '1mb' }));

app.get('/health', (_req, res) => res.json({ status: 'ok', service: 'auth-svc' }));
app.get('/ready', (_req, res) => res.json({ status: 'ready' }));

app.use((err: unknown, _req: express.Request, res: express.Response, _next: express.NextFunction) => {
  console.error('[auth-svc] Unhandled error:', err);
  res.status(500).json({
    error: 'Internal server error',
    message: err instanceof Error ? err.message : String(err),
  });
});

app.listen(PORT, '0.0.0.0', () => {
  console.log(`auth-svc listening on :${PORT}`);
  console.log('  GET /api/auth/me — Bearer validation for library-svc, memory-svc, etc.');
  console.log('  Перед первым запуском: cd services/auth-svc && npm run db:migrate');
});
