/**
 * Jobs Routes - Job listing and details
 */

import { Hono } from 'hono';
import { jobsService } from '../services/jobsService';
import { authMiddleware, getUserId } from '../middleware/auth';
import { BadRequestError, NotFoundError } from '../middleware/errorHandler';

const jobs = new Hono();

// All job routes require authentication
jobs.use('/*', authMiddleware);

/**
 * GET /api/jobs
 * List all jobs for the user
 */
jobs.get('/', async (c) => {
  const page = parseInt(c.req.query('page') || '1');
  const limit = parseInt(c.req.query('limit') || '50');

  const result = await jobsService.getJobs({ page, perPage: limit });

  return c.json(result);
});

/**
 * GET /api/jobs/search
 * Search jobs by query
 */
jobs.get('/search', async (c) => {
  const query = c.req.query('q');

  if (!query) {
    throw new BadRequestError('Search query required');
  }

  const jobs = await jobsService.searchJobs(query);

  return c.json({ jobs, page: 1, perPage: jobs.length, totalItems: jobs.length, totalPages: 1 });
});

/**
 * GET /api/jobs/:id
 * Get single job with all details
 */
jobs.get('/:id', async (c) => {
  const userId = getUserId(c);
  const jobId = c.req.param('id');

  const result = await jobsService.getJobDetail(jobId, userId);

  if (!result) {
    throw new NotFoundError('Job not found');
  }

  return c.json(result);
});

/**
 * GET /api/jobs/:id/files
 * Get files for a job from SharePoint
 */
jobs.get('/:id/files', async (c) => {
  const userId = getUserId(c);
  const jobId = c.req.param('id');

  const result = await jobsService.getJobFiles(jobId, userId);

  return c.json({ files: result?.files ?? [] });
});

/**
 * POST /api/jobs/:id/notes
 * Create a sticky note on a job
 */
jobs.post('/:id/notes', async (c) => {
  const userId = getUserId(c);
  const jobId = c.req.param('id');
  const body = await c.req.json<{ content: string; color?: string }>();

  if (!body.content) {
    throw new BadRequestError('Note content required');
  }

  const note = await jobsService.createNote(
    jobId, 
    body.content, 
    userId, 
    { color: body.color as 'yellow' | 'blue' | 'green' | 'pink' | 'purple' | undefined }
  );

  return c.json({ note });
});

/**
 * PUT /api/jobs/:id/notes/:noteId
 * Update a sticky note
 */
jobs.put('/:id/notes/:noteId', async (c) => {
  const noteId = c.req.param('noteId');
  const body = await c.req.json<{ content?: string; color?: 'yellow' | 'blue' | 'green' | 'pink' | 'purple' }>();

  const note = await jobsService.updateNote(noteId, body);

  return c.json({ note });
});

/**
 * DELETE /api/jobs/:id/notes/:noteId
 * Delete a sticky note
 */
jobs.delete('/:id/notes/:noteId', async (c) => {
  const noteId = c.req.param('noteId');

  await jobsService.deleteNote(noteId);

  return c.json({ success: true });
});

export default jobs;
