import { Hono } from 'hono';
import {
  TaskQuerySchema,
  BulkTaskSchema,
  CompleteTaskSchema,
  ReassignTaskSchema,
} from '../types/index';
import * as taskService from '../services/task.service';

export const tasksRouter = new Hono();

// ─── GET /v1/tasks ──────────────────────────────────────
// List tasks (the decision queue)
tasksRouter.get('/', async (c) => {
  try {
    const raw = c.req.query();
    const auth = c.get('auth');

    // Support "me" as assigneeId
    if (raw.assigneeId === 'me' && auth?.userId) {
      raw.assigneeId = auth.userId;
    }

    const query = TaskQuerySchema.parse(raw);
    const result = await taskService.listTasks(query);

    return c.json({
      success: true,
      data: result.items,
      meta: result.meta,
    });
  } catch (err: any) {
    if (err.name === 'ZodError') {
      return c.json(
        { success: false, error: { code: 'VALIDATION_ERROR', message: 'Invalid query', details: err.errors } },
        400
      );
    }
    return c.json(
      { success: false, error: { code: 'INTERNAL_ERROR', message: err.message } },
      500
    );
  }
});

// ─── GET /v1/tasks/stats ────────────────────────────────
// Task queue statistics
tasksRouter.get('/stats', async (c) => {
  try {
    const stats = await taskService.getTaskStats();
    return c.json({ success: true, data: stats });
  } catch (err: any) {
    return c.json(
      { success: false, error: { code: 'INTERNAL_ERROR', message: err.message } },
      500
    );
  }
});

// ─── POST /v1/tasks/bulk ────────────────────────────────
// Bulk operations on tasks (approve/reject/defer)
tasksRouter.post('/bulk', async (c) => {
  try {
    const body = BulkTaskSchema.parse(await c.req.json());
    const auth = c.get('auth');

    const results = await taskService.bulkAction(
      body.action,
      body.taskIds,
      auth.userId,
      { notes: body.notes }
    );

    return c.json({ success: true, data: results });
  } catch (err: any) {
    if (err.name === 'ZodError') {
      return c.json(
        { success: false, error: { code: 'VALIDATION_ERROR', message: 'Invalid input', details: err.errors } },
        400
      );
    }
    return c.json(
      { success: false, error: { code: 'INTERNAL_ERROR', message: err.message } },
      500
    );
  }
});

// ─── GET /v1/tasks/blockers ─────────────────────────────
// Get all blocking items across pipelines
tasksRouter.get('/blockers', async (c) => {
  try {
    const pipelineId = c.req.query('pipeline_id');
    const blockers = await taskService.getBlockers(pipelineId);
    return c.json({ success: true, data: blockers });
  } catch (err: any) {
    return c.json(
      { success: false, error: { code: 'INTERNAL_ERROR', message: err.message } },
      500
    );
  }
});

// ─── GET /v1/tasks/:id ─────────────────────────────────
// Get task details with full context
tasksRouter.get('/:id', async (c) => {
  try {
    const task = await taskService.getTask(c.req.param('id'));

    if (!task) {
      return c.json(
        { success: false, error: { code: 'NOT_FOUND', message: 'Task not found' } },
        404
      );
    }

    return c.json({ success: true, data: task });
  } catch (err: any) {
    return c.json(
      { success: false, error: { code: 'INTERNAL_ERROR', message: err.message } },
      500
    );
  }
});

// ─── POST /v1/tasks/:id/claim ───────────────────────────
// Claim a task
tasksRouter.post('/:id/claim', async (c) => {
  try {
    const auth = c.get('auth');
    const task = await taskService.claimTask(c.req.param('id'), auth.userId);
    return c.json({ success: true, data: task });
  } catch (err: any) {
    if (err.message.includes('not found')) {
      return c.json(
        { success: false, error: { code: 'NOT_FOUND', message: err.message } },
        404
      );
    }
    if (err.message.includes('not pending') || err.message.includes('claimed by someone')) {
      return c.json(
        { success: false, error: { code: 'CONFLICT', message: err.message } },
        409
      );
    }
    return c.json(
      { success: false, error: { code: 'INTERNAL_ERROR', message: err.message } },
      500
    );
  }
});

// ─── POST /v1/tasks/:id/complete ────────────────────────
// Complete a task with decision
tasksRouter.post('/:id/complete', async (c) => {
  try {
    const body = CompleteTaskSchema.parse(await c.req.json());
    const auth = c.get('auth');

    const task = await taskService.completeTask(
      c.req.param('id'),
      body.decision,
      auth.userId,
      { notes: body.notes, data: body.decisionData }
    );

    return c.json({ success: true, data: task });
  } catch (err: any) {
    if (err.name === 'ZodError') {
      return c.json(
        { success: false, error: { code: 'VALIDATION_ERROR', message: 'Invalid input', details: err.errors } },
        400
      );
    }
    if (err.message.includes('not found')) {
      return c.json(
        { success: false, error: { code: 'NOT_FOUND', message: err.message } },
        404
      );
    }
    if (err.message.includes('already completed')) {
      return c.json(
        { success: false, error: { code: 'CONFLICT', message: err.message } },
        409
      );
    }
    return c.json(
      { success: false, error: { code: 'INTERNAL_ERROR', message: err.message } },
      500
    );
  }
});

// ─── POST /v1/tasks/:id/reassign ────────────────────────
// Reassign a task to another user
tasksRouter.post('/:id/reassign', async (c) => {
  try {
    const body = ReassignTaskSchema.parse(await c.req.json());
    const auth = c.get('auth');

    const task = await taskService.reassignTask(
      c.req.param('id'),
      body.assigneeId,
      auth.userId,
      body.reason
    );

    return c.json({ success: true, data: task });
  } catch (err: any) {
    if (err.name === 'ZodError') {
      return c.json(
        { success: false, error: { code: 'VALIDATION_ERROR', message: 'Invalid input', details: err.errors } },
        400
      );
    }
    if (err.message.includes('not found')) {
      return c.json(
        { success: false, error: { code: 'NOT_FOUND', message: err.message } },
        404
      );
    }
    if (err.message.includes('completed')) {
      return c.json(
        { success: false, error: { code: 'CONFLICT', message: err.message } },
        409
      );
    }
    return c.json(
      { success: false, error: { code: 'INTERNAL_ERROR', message: err.message } },
      500
    );
  }
});
