import { Router } from 'express';
import { z } from 'zod';
import { db } from '../../db/knex';
import { forbidden, notFound, validationError } from '../../lib/http-errors';
import { settingsSchema, userSchema } from '../../shared/schemas';
import { requireRole } from '../../middleware/auth';
import { validate } from '../../middleware/validate';
import { audit } from './audit';
import { adminPage, idParam, paged, write } from './helpers';
import { messageStatusToDb, toActivity, toAdminUser, toInboxRequest } from './mappers';

const adminsOnly = requireRole('admin');
const n = async (q: ReturnType<typeof db>) =>
  Number(((await q.count({ n: '*' }).first()) as { n: number }).n);

export function systemRouter() {
  const r = Router();

  /* ---------- dashboard ---------- */
  r.get('/dashboard', async (_req, res) => {
    const [brands, placeholders, generics, approved, companies, openRequests, noPrice, noImage, vet, agro] =
      await Promise.all([
        n(db('brands').where('catalogue', 'human')),
        n(db('brands').where('name', 'like', '[%')),
        n(db('generics')),
        n(db('generics').where('review_status', 'approved')),
        n(db('companies').whereNot('name', 'like', '[%')),
        n(db('contact_messages').whereNot('status', 'resolved')),
        n(db('brands').where('catalogue', 'human').whereNull('unit_price')),
        n(
          db('brands')
            .where('catalogue', 'human')
            .whereNotExists(db('brand_images').whereRaw('brand_images.brand_id = brands.id')),
        ),
        n(db('brands').where('catalogue', 'vet')),
        n(db('brands').where('catalogue', 'agro')),
      ]);
    const byForm = (await db('brands as b')
      .leftJoin('dosage_forms as df', 'df.id', 'b.dosage_form_id')
      .select(db.raw('coalesce(df.name, b.form_label) as label'))
      .count({ count: '*' })
      .where('b.catalogue', 'human')
      .groupByRaw('coalesce(df.name, b.form_label)')
      .orderBy('count', 'desc')
      .limit(7)) as unknown as { label: string; count: number }[];
    const pending = await db('generics')
      .select('id', 'slug', 'name')
      .where('review_status', 'pending')
      .orderBy('updated_at', 'desc')
      .limit(5);
    const inbox = await db('contact_messages')
      .select('*')
      .whereNot('status', 'resolved')
      .orderBy('created_at', 'desc')
      .limit(5);
    const activity = await db('audit_log as a')
      .leftJoin('admins as ad', 'ad.id', 'a.admin_id')
      .select('a.*', 'ad.name as admin_name')
      .whereNot('a.action', 'login')
      .orderBy('a.created_at', 'desc')
      .limit(6);
    res.json({
      brands,
      placeholders,
      generics,
      approved,
      pendingReview: generics - approved,
      companies,
      openRequests,
      noPrice,
      noImage,
      vet,
      agro,
      byForm: byForm.map((f) => ({ label: f.label, count: Number(f.count) })),
      pending: pending.map((g: { id: string; slug: string; name: string }) => ({
        id: String(g.id),
        slug: g.slug,
        name: g.name,
      })),
      inbox: inbox.map(toInboxRequest),
      activity: activity.map(toActivity),
    });
  });

  /* ---------- audit log (read-only) ---------- */
  /* ---------- 404 log (SEO Phase 13): broken links and missing medicines ---------- */
  const nfList = adminPage.extend({ sort: z.enum(['recent', 'hits']).default('recent') });
  r.get('/not-found', validate({ query: nfList }), async (_req, res) => {
    const q = res.locals.valid!.query as z.infer<typeof nfList>;
    const qb = db('not_found_log').select('*');
    if (q.q) qb.where('path', 'like', `%${q.q}%`);
    if (q.sort === 'hits') qb.orderBy('hits', 'desc');
    qb.orderBy('last_seen_at', 'desc');
    res.json(
      await paged(qb, q, (r: Record<string, never>) => ({
        id: String(r.id),
        path: r.path,
        referrer: r.referrer ?? null,
        hits: Number(r.hits),
        firstSeen: String(r.first_seen_at).replace(' ', 'T'),
        lastSeen: String(r.last_seen_at).replace(' ', 'T'),
      })),
    );
  });
  r.delete('/not-found', adminsOnly, async (_req, res) => {
    const n = await db('not_found_log').del();
    await audit({
      adminId: res.locals.admin!.id,
      action: 'cleared',
      entity: 'not_found_log',
      label: `${n} entries`,
    });
    res.status(204).end();
  });

  r.get('/audit-log', validate({ query: adminPage }), async (_req, res) => {
    const q = res.locals.valid!.query as z.infer<typeof adminPage>;
    const qb = db('audit_log as a')
      .leftJoin('admins as ad', 'ad.id', 'a.admin_id')
      .select('a.*', 'ad.name as admin_name')
      .orderBy('a.created_at', 'desc')
      .orderBy('a.id', 'desc');
    if (q.q)
      qb.where((w) =>
        w
          .where('a.label', 'like', `%${q.q}%`)
          .orWhere('ad.name', 'like', `%${q.q}%`)
          .orWhere('a.action', 'like', `%${q.q}%`),
      );
    res.json(await paged(qb, q, toActivity));
  });

  /* ---------- inbox (contact messages) ---------- */
  const msgList = adminPage.extend({ status: z.enum(['open', 'resolved']).optional() });
  r.get('/messages', validate({ query: msgList }), async (_req, res) => {
    const q = res.locals.valid!.query as z.infer<typeof msgList>;
    const qb = db('contact_messages').select('*').orderBy('created_at', 'desc');
    if (q.status === 'open') qb.whereNot('status', 'resolved');
    if (q.status === 'resolved') qb.where('status', 'resolved');
    if (q.q) qb.where('message', 'like', `%${q.q}%`);
    res.json(await paged(qb, q, toInboxRequest));
  });
  r.patch(
    '/messages/:id',
    validate({ params: idParam, body: z.object({ status: z.enum(['new', 'in-progress', 'resolved']) }) }),
    async (_req, res) => {
      const id = res.locals.valid!.params.id as string;
      const { status } = res.locals.valid!.body as { status: string };
      const m = await db('contact_messages').where({ id }).first();
      if (!m) throw notFound('Message not found.');
      await write(async (trx) => {
        await trx('contact_messages')
          .where({ id })
          .update({ status: messageStatusToDb(status) });
        await audit(
          {
            adminId: res.locals.admin!.id,
            action: 'updated',
            entity: 'message',
            entityId: id,
            label: `message → ${status}`,
          },
          trx,
        );
      });
      res.json(toInboxRequest(await db('contact_messages').where({ id }).first()));
    },
  );

  /* ---------- users & roles (Q1) ---------- */
  r.get('/users', adminsOnly, async (_req, res) =>
    res.json({
      items: (
        await db('admins').select('id', 'name', 'email', 'role', 'status', 'last_login_at').orderBy('name')
      ).map(toAdminUser),
    }),
  );
  const saveUser = async (v: z.infer<typeof userSchema>, me: { id: string }, id?: string) =>
    write(async (trx) => {
      const clash = await trx('admins')
        .where({ email: v.email.toLowerCase() })
        .modify((q) => id && q.whereNot('id', id))
        .first();
      if (clash) throw validationError({ email: ['A user with this email already exists.'] });
      if (id === me.id && (v.role !== 'admin' || v.status !== 'active'))
        throw validationError({ role: ['You can’t remove your own admin access.'] });
      const row = { name: v.name, email: v.email.toLowerCase(), role: v.role, status: v.status };
      if (id) await trx('admins').where({ id }).update(row);
      else [id] = await trx('admins').insert({ ...row, password_hash: null }); // invited: sets a password via the invite/reset flow
      await audit(
        { adminId: me.id, action: id ? 'saved' : 'invited', entity: 'user', entityId: id, label: v.email },
        trx,
      );
      return String(id);
    });
  r.post('/users', adminsOnly, validate({ body: userSchema }), async (_req, res) => {
    const id = await saveUser(res.locals.valid!.body as z.infer<typeof userSchema>, res.locals.admin!);
    res.status(201).json(toAdminUser(await db('admins').where({ id }).first()));
  });
  r.put('/users/:id', adminsOnly, validate({ params: idParam, body: userSchema }), async (_req, res) => {
    const id = res.locals.valid!.params.id as string;
    if (!(await db('admins').where({ id }).first())) throw notFound('User not found.');
    await saveUser(res.locals.valid!.body as z.infer<typeof userSchema>, res.locals.admin!, id);
    res.json(toAdminUser(await db('admins').where({ id }).first()));
  });
  r.delete('/users/:id', adminsOnly, validate({ params: idParam }), async (_req, res) => {
    const id = res.locals.valid!.params.id as string;
    if (id === res.locals.admin!.id) throw forbidden('You can’t remove yourself.');
    const u = await db('admins').where({ id }).first();
    if (!u) throw notFound('User not found.');
    await write(async (trx) => {
      await trx('admins').where({ id }).del();
      await audit(
        { adminId: res.locals.admin!.id, action: 'deleted', entity: 'user', entityId: id, label: u.email },
        trx,
      );
    });
    res.status(204).end();
  });

  /* ---------- settings ---------- */
  const readSettings = async () => {
    const rows = await db('settings').select('key', 'value');
    return Object.fromEntries(
      rows.map((r: { key: string; value: unknown }) => [
        r.key,
        typeof r.value === 'string' ? JSON.parse(r.value) : r.value,
      ]),
    );
  };
  r.get('/settings', adminsOnly, async (_req, res) => res.json(await readSettings()));
  r.put('/settings', adminsOnly, validate({ body: settingsSchema }), async (_req, res) => {
    const v = res.locals.valid!.body as Record<string, unknown>;
    await write(async (trx) => {
      for (const [key, value] of Object.entries(v)) {
        await trx('settings')
          .insert({ key, value: JSON.stringify(value) })
          .onConflict('key')
          .merge({ value: JSON.stringify(value) });
      }
      await audit(
        {
          adminId: res.locals.admin!.id,
          action: 'updated',
          entity: 'settings',
          label: 'site settings',
          diff: v,
        },
        trx,
      );
    });
    res.json(await readSettings());
  });

  return r;
}
