import 'dotenv/config';
import express from 'express';
import cors from 'cors';
import helmet from 'helmet';
import pino from 'pino';
import pinoHttp from 'pino-http';
import { DeviceRegistry } from './services/device-registry.js';
import { ZktecoGateway } from './services/zkteco-gateway.js';

const logger = pino({ level: process.env.LOG_LEVEL || 'info' });
const app = express();
const registry = new DeviceRegistry();
const gateway = new ZktecoGateway({ registry, logger });

app.use(helmet());
app.use(cors());
app.use(express.json({ limit: '2mb' }));
app.use(pinoHttp({ logger }));

app.get('/health', (req, res) => {
  res.json({ status: 'ok', service: 'zkteco-device-service' });
});

app.post('/devices/register', async (req, res) => {
  const device = await registry.register(req.body);
  res.status(201).json(device);
});

app.post('/devices/:serialNo/pull-logs', async (req, res) => {
  const result = await gateway.pullLogs(req.params.serialNo);
  res.json(result);
});

app.post('/devices/:serialNo/push-user', async (req, res) => {
  const result = await gateway.pushUser(req.params.serialNo, req.body);
  res.json(result);
});

app.post('/devices/:serialNo/restart', async (req, res) => {
  const result = await gateway.restart(req.params.serialNo);
  res.json(result);
});

app.post('/devices/:serialNo/attendance-webhook', async (req, res) => {
  const result = await gateway.receivePushLog(req.params.serialNo, req.body);
  res.status(202).json(result);
});

const port = Number(process.env.PORT || 8090);
app.listen(port, () => logger.info({ port }, 'device service started'));
