import { Router } from 'express';
import Stripe from 'stripe';
import { prisma } from '../config/database.js';
import { authenticate } from '../middleware/auth.js';
import { env } from '../config/env.js';
import { AppError } from '../middleware/errorHandler.js';

const router = Router();

const stripe = env.STRIPE_SECRET_KEY ? new Stripe(env.STRIPE_SECRET_KEY) : null;

// --- List payouts ---
router.get('/', authenticate, async (req, res, next) => {
  try {
    const payouts = await prisma.payout.findMany({
      where: { landlordId: req.userId },
      include: {
        booking: {
          select: {
            id: true,
            rentalListing: { select: { id: true, title: true } },
            tenant: { select: { id: true, fullName: true } },
            startDate: true, endDate: true,
          },
        },
      },
      orderBy: { createdAt: 'desc' },
    });
    res.json(payouts);
  } catch (error) {
    next(error);
  }
});

// --- Get payout details ---
router.get('/:id', authenticate, async (req, res, next) => {
  try {
    const payout = await prisma.payout.findUnique({
      where: { id: req.params.id },
      include: {
        booking: {
          select: {
            id: true,
            rentalListing: { select: { id: true, title: true } },
            tenant: { select: { id: true, fullName: true } },
            startDate: true, endDate: true, totalAmount: true, subtotal: true,
          },
        },
      },
    });
    if (!payout) throw new AppError(404, 'Payout not found');
    if (payout.landlordId !== req.userId) throw new AppError(403, 'Not authorized');

    res.json(payout);
  } catch (error) {
    next(error);
  }
});

// --- Setup Stripe Connect account ---
router.post('/setup-account', authenticate, async (req, res, next) => {
  try {
    if (!stripe) throw new AppError(500, 'Stripe not configured');

    const user = await prisma.user.findUnique({ where: { id: req.userId } });
    if (!user) throw new AppError(404, 'User not found');

    let accountId = user.stripeAccountId;

    if (!accountId) {
      const account = await stripe.accounts.create({
        type: 'express',
        email: user.email,
        metadata: { userId: user.id },
      });
      accountId = account.id;
      await prisma.user.update({ where: { id: req.userId }, data: { stripeAccountId: accountId } });
    }

    const accountLink = await stripe.accountLinks.create({
      account: accountId,
      refresh_url: `${env.CLIENT_URL}/landlord/payouts`,
      return_url: `${env.CLIENT_URL}/landlord/payouts`,
      type: 'account_onboarding',
    });

    res.json({ url: accountLink.url });
  } catch (error) {
    next(error);
  }
});

// --- Check Stripe Connect account status ---
router.get('/account-status', authenticate, async (req, res, next) => {
  try {
    if (!stripe) throw new AppError(500, 'Stripe not configured');

    const user = await prisma.user.findUnique({ where: { id: req.userId } });
    if (!user?.stripeAccountId) {
      return res.json({ connected: false, detailsSubmitted: false, chargesEnabled: false, payoutsEnabled: false });
    }

    const account = await stripe.accounts.retrieve(user.stripeAccountId);

    res.json({
      connected: true,
      detailsSubmitted: account.details_submitted,
      chargesEnabled: account.charges_enabled,
      payoutsEnabled: account.payouts_enabled,
    });
  } catch (error) {
    next(error);
  }
});

export default router;
