import { NextRequest, NextResponse } from 'next/server';
import { changeOwnerSchema } from '@/lib/validators';
import { getSession } from '@/lib/auth';
import { changeCompanyOwner, isCompanyOwner } from '@/lib/companies';

/**
 * PATCH /api/companies/[id]/owner
 * Change the company owner
 * - Current owner only: can transfer ownership to another company member
 * - New owner must be an existing user in the same company
 */
export async function PATCH(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;

    // Verify authentication
    const accessToken = request.cookies.get('scriba.access_token')?.value;
    const sessionData = await getSession(accessToken);

    if (!sessionData) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const { user } = sessionData;

    // Verify user belongs to this company
    if (user.companyId !== id) {
      return NextResponse.json(
        { error: 'Access denied. You are not a member of this company.' },
        { status: 403 }
      );
    }

    // Verify ownership
    const isOwner = await isCompanyOwner(user.id, id);
    if (!isOwner) {
      return NextResponse.json(
        { error: 'Only the current owner can transfer ownership' },
        { status: 403 }
      );
    }

    // Parse and validate request body
    const body = await request.json();
    const parsed = changeOwnerSchema.safeParse(body);

    if (!parsed.success) {
      return NextResponse.json(
        { error: parsed.error.issues[0]?.message ?? 'Invalid input' },
        { status: 400 }
      );
    }

    const { newOwnerId } = parsed.data;

    // Change owner
    const result = await changeCompanyOwner(id, user.id, newOwnerId);

    if (!result.success) {
      return NextResponse.json(
        { error: result.error },
        { status: 400 }
      );
    }

    return NextResponse.json({
      success: true,
      message: 'Ownership transferred successfully',
      newOwnerId,
    });

  } catch (error) {
    console.error('Change owner error:', error);
    return NextResponse.json(
      { error: 'Failed to transfer ownership' },
      { status: 500 }
    );
  }
}
