import { Router, Request, Response } from 'express';
import { asyncHandler } from '../utils/asyncHandler';
import { db } from '../db';
import { repeatProfiles } from '../db/schema';
import { eq, and, asc } from 'drizzle-orm';
import { authMiddleware } from '../utils/auth';
import { generateId } from '../utils/auth';
import { AppError } from '../middleware/errorHandler';
import { repeatProfileSchema, repeatProfileUpdateSchema } from '../utils/validation';

const router = Router();

router.use(authMiddleware);

router.get('/', asyncHandler(async (req: Request, res: Response) => {
  const profiles = await db
    .select()
    .from(repeatProfiles)
    .where(eq(repeatProfiles.userId, req.user!.userId))
    .orderBy(asc(repeatProfiles.createdAt));

  res.json({ profiles });
}));

router.post('/', asyncHandler(async (req: Request, res: Response) => {
  const data = repeatProfileSchema.parse(req.body);
  const userId = req.user!.userId;
  const now = Date.now();

  const newProfile = {
    id: generateId('rp'),
    userId,
    name: data.name,
    repeat: data.repeat,
    repeatInterval: data.repeatInterval,
    repeatDays: data.repeatDays,
    createdAt: now,
    updatedAt: now,
  };

  await db.insert(repeatProfiles).values(newProfile);

  res.status(201).json(newProfile);
}));

router.patch('/:id', asyncHandler(async (req: Request, res: Response) => {
  const data = repeatProfileUpdateSchema.parse(req.body);
  const userId = req.user!.userId;

  const existing = await db
    .select()
    .from(repeatProfiles)
    .where(and(eq(repeatProfiles.id, req.params.id), eq(repeatProfiles.userId, userId)))
    .limit(1);

  if (existing.length === 0) {
    throw new AppError('NOT_FOUND', 'Repeat profile not found', 404);
  }

  const now = Date.now();
  const updated = await db
    .update(repeatProfiles)
    .set({ ...data, updatedAt: now })
    .where(and(eq(repeatProfiles.id, req.params.id), eq(repeatProfiles.userId, userId)))
    .returning();

  res.json(updated[0]);
}));

router.delete('/:id', asyncHandler(async (req: Request, res: Response) => {
  const userId = req.user!.userId;

  const existing = await db
    .select()
    .from(repeatProfiles)
    .where(and(eq(repeatProfiles.id, req.params.id), eq(repeatProfiles.userId, userId)))
    .limit(1);

  if (existing.length === 0) {
    throw new AppError('NOT_FOUND', 'Repeat profile not found', 404);
  }

  await db
    .delete(repeatProfiles)
    .where(and(eq(repeatProfiles.id, req.params.id), eq(repeatProfiles.userId, userId)));

  res.status(204).send();
}));

export default router;
