import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/db';

export const dynamic = 'force-dynamic';

async function verifyPermission(request: NextRequest, permission: string): Promise<{ valid: boolean; userId?: string }> {
  const authHeader = request.headers.get('authorization');
  const token = authHeader?.replace('Bearer ', '');
  
  if (!token) return { valid: false };
  
  const accessToken = await prisma.tesAccessToken.findUnique({
    where: { token }
  });
  
  if (!accessToken || !accessToken.isActive) return { valid: false };
  
  const permissions = JSON.parse(accessToken.permissions);
  if (!permissions.includes(permission) && !permissions.includes('admin')) {
    return { valid: false };
  }
  
  return { valid: true, userId: accessToken.userId };
}

// GET - Read diary entries
export async function GET(request: NextRequest) {
  try {
    const auth = await verifyPermission(request, 'diary');
    if (!auth.valid) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }
    
    const { searchParams } = new URL(request.url);
    const date = searchParams.get('date');
    const limit = parseInt(searchParams.get('limit') || '7');
    
    let entries;
    if (date) {
      // Get specific date
      const targetDate = new Date(date);
      entries = await prisma.tesDiary.findFirst({
        where: { date: targetDate }
      });
      return NextResponse.json({ entry: entries });
    } else {
      // Get recent entries
      entries = await prisma.tesDiary.findMany({
        orderBy: { date: 'desc' },
        take: limit
      });
      return NextResponse.json({ entries });
    }
  } catch (error) {
    console.error('Diary read error:', error);
    return NextResponse.json({ error: 'Failed to read diary' }, { status: 500 });
  }
}

// POST - Create/update diary entry
export async function POST(request: NextRequest) {
  try {
    const auth = await verifyPermission(request, 'admin');
    if (!auth.valid) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }
    
    const { date, mood, content, isPrivate } = await request.json();
    
    if (!content) {
      return NextResponse.json({ error: 'Content required' }, { status: 400 });
    }
    
    const entryDate = date ? new Date(date) : new Date();
    // Normalize to just the date part
    entryDate.setHours(0, 0, 0, 0);
    
    const entry = await prisma.tesDiary.upsert({
      where: { date: entryDate },
      update: { mood, content, isPrivate: isPrivate ?? true },
      create: { date: entryDate, mood, content, isPrivate: isPrivate ?? true }
    });
    
    return NextResponse.json({ success: true, entry });
  } catch (error) {
    console.error('Diary write error:', error);
    return NextResponse.json({ error: 'Failed to write diary' }, { status: 500 });
  }
}
