/**
 * Translate Press Zone licensing endpoints.
 *
 * Base path: /v1/translate/license
 */

import { Router, Request, Response } from 'express';
import { z } from 'zod';
import { validate } from '../middleware/validator';
import { errorResponse, successResponse } from '../utils/errorHandler';
import { activateLicense, deactivateLicense, validateLicense } from '../services/multilingualLicenseService';
import { createRateLimiter } from '../middleware/rateLimiter';

const router = Router();
const licenseActivateRateLimiter = createRateLimiter(15 * 60 * 1000, 30);
const licenseValidateRateLimiter = createRateLimiter(15 * 60 * 1000, 100);

const licenseKeySchema = z
  .string()
  .regex(/^TRAN-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}$/, 'Invalid license key format');
const siteUrlSchema = z.string().url('site_url must be a valid URL');
const activateSchema = z.object({
  license_key: licenseKeySchema,
  site_url: siteUrlSchema,
  product: z.string().optional(),
  version: z.string().optional(),
});
const deactivateSchema = z.object({
  license_key: licenseKeySchema,
  site_url: siteUrlSchema,
  product: z.string().optional(),
});
const validateSchema = z.object({
  license_key: licenseKeySchema,
  site_url: siteUrlSchema,
  product: z.string().optional(),
});

function mapServiceError(err: unknown): { status: number; body: any } {
  const code = err instanceof Error ? err.message : 'UNKNOWN_ERROR';
  switch (code) {
    case 'INVALID_LICENSE':
      return { status: 404, body: errorResponse('INVALID_LICENSE', 'The license key is invalid') };
    case 'LICENSE_EXPIRED':
      return { status: 403, body: errorResponse('LICENSE_EXPIRED', 'This license has expired') };
    case 'LICENSE_NOT_ACTIVE':
      return { status: 403, body: errorResponse('LICENSE_NOT_ACTIVE', 'This license is not active') };
    case 'SUBSCRIPTION_REQUIRED':
      return { status: 403, body: errorResponse('SUBSCRIPTION_REQUIRED', 'An active subscription is required') };
    case 'LICENSE_OWNER_AMBIGUOUS':
      return { status: 409, body: errorResponse('LICENSE_OWNER_AMBIGUOUS', 'The license owner could not be resolved') };
    case 'SITE_LIMIT_REACHED':
      return { status: 409, body: errorResponse('SITE_LIMIT_REACHED', 'This license has reached its site limit') };
    default:
      return { status: 500, body: errorResponse('INTERNAL_ERROR', 'Failed to process license request') };
  }
}

router.post('/activate', licenseActivateRateLimiter, validate(activateSchema), async (req: Request, res: Response) => {
  try {
    const info = await activateLicense({
      license_key: req.body.license_key,
      site_url: req.body.site_url,
      plugin: 'translate',
    });
    return res.status(200).json(successResponse(info));
  } catch (err) {
    const mapped = mapServiceError(err);
    return res.status(mapped.status).json(mapped.body);
  }
});

router.post('/deactivate', licenseActivateRateLimiter, validate(deactivateSchema), async (req: Request, res: Response) => {
  try {
    await deactivateLicense({
      license_key: req.body.license_key,
      site_url: req.body.site_url,
      plugin: 'translate',
    });
    return res.status(200).json(successResponse({ success: true }));
  } catch (err) {
    const mapped = mapServiceError(err);
    return res.status(mapped.status).json(mapped.body);
  }
});

router.post('/validate', licenseValidateRateLimiter, validate(validateSchema), async (req: Request, res: Response) => {
  try {
    const info = await validateLicense({
      license_key: req.body.license_key,
      site_url: req.body.site_url,
      plugin: 'translate',
    });
    return res.status(200).json(successResponse(info));
  } catch (err) {
    const mapped = mapServiceError(err);
    return res.status(mapped.status).json(mapped.body);
  }
});

router.get('/status', licenseValidateRateLimiter, async (req: Request, res: Response) => {
  const license_key = typeof req.query.license_key === 'string' ? req.query.license_key.trim() : '';
  const site_url = typeof req.query.site_url === 'string' ? req.query.site_url.trim() : '';

  if (!license_key && !site_url) {
    return res.status(200).json(successResponse({ ok: true }));
  }
  if (!license_key || !site_url) {
    return res.status(200).json(successResponse({
      ok: true,
      validation: { ok: false, message: 'Provide both license_key and site_url to validate a license' },
    }));
  }

  const parsed = validateSchema.safeParse({ license_key, site_url });
  if (!parsed.success) {
    return res.status(200).json(successResponse({
      ok: true,
      validation: {
        ok: false,
        issues: parsed.error.issues.map(issue => ({ path: issue.path.join('.'), message: issue.message })),
      },
    }));
  }

  try {
    const info = await validateLicense({
      license_key: parsed.data.license_key,
      site_url: parsed.data.site_url,
      plugin: 'translate',
    });
    return res.status(200).json(successResponse({
      ok: true,
      license: { status: info.status, valid: info.status === 'active' },
    }));
  } catch (err) {
    const mapped = mapServiceError(err);
    return res.status(mapped.status).json(mapped.body);
  }
});

export default router;
