import { Router } from 'express';
import { db } from '../lib/db.js';
import { requireAuth, AuthedRequest } from '../middleware/auth.js';

export const partnersRouter = Router();

// Send a partner request (not via link) by target uid
partnersRouter.post('/request', requireAuth, (req: AuthedRequest, res) => {
  const { toUid } = req.body as { toUid?: string };
  const fromUid = req.user?.uid;
  if (!fromUid || !toUid || fromUid === toUid) return res.status(400).json({ error: 'Invalid uids' });

  const now = Date.now();
  try {
    db.db
      .prepare(
        `INSERT INTO friend_requests (from_user_id, to_user_id, status, created_at, updated_at)
         VALUES (?, ?, 'pending', ?, ?)`
      )
      .run(fromUid, toUid, now, now);
    res.json({ ok: true });
  } catch (e: any) {
    if (e && String(e.message).includes('UNIQUE')) {
      return res.status(409).json({ error: 'Request already exists' });
    }
    throw e;
  }
});

// List incoming requests for a user
partnersRouter.get('/requests/:uid', requireAuth, (req: AuthedRequest, res) => {
  const { uid } = req.params;
  if (!req.user || req.user.uid !== uid) return res.status(403).json({ error: 'Forbidden' });
  const rows = db.db
    .prepare("SELECT id, from_user_id, to_user_id, status, created_at FROM friend_requests WHERE to_user_id = ? AND status = 'pending' ORDER BY created_at DESC")
    .all(uid);
  res.json(rows);
});

// Accept a request
partnersRouter.post('/requests/:id/accept', requireAuth, (req: AuthedRequest, res) => {
  const { id } = req.params;
  const reqRow = db.db.prepare('SELECT * FROM friend_requests WHERE id = ?').get(id) as any;
  if (!reqRow) return res.status(404).json({ error: 'Not found' });
  if (!req.user || req.user.uid !== reqRow.to_user_id) return res.status(403).json({ error: 'Forbidden' });

  const now = Date.now();
  const userA = reqRow.from_user_id < reqRow.to_user_id ? reqRow.from_user_id : reqRow.to_user_id;
  const userB = reqRow.from_user_id < reqRow.to_user_id ? reqRow.to_user_id : reqRow.from_user_id;

  const txn = db.db.transaction(() => {
    db.db.prepare("UPDATE friend_requests SET status='accepted', updated_at=? WHERE id=?").run(now, id);
    db.db.prepare('INSERT OR IGNORE INTO friendships (user_a_id, user_b_id, created_at) VALUES (?, ?, ?)').run(userA, userB, now);
  });
  txn();

  res.json({ ok: true });
});

// Decline a request
partnersRouter.post('/requests/:id/decline', requireAuth, (req: AuthedRequest, res) => {
  const { id } = req.params;
  const now = Date.now();
  const reqRow = db.db.prepare('SELECT * FROM friend_requests WHERE id = ?').get(id) as any;
  if (!reqRow) return res.status(404).json({ error: 'Not found' });
  if (!req.user || req.user.uid !== reqRow.to_user_id) return res.status(403).json({ error: 'Forbidden' });
  db.db.prepare("UPDATE friend_requests SET status='declined', updated_at=? WHERE id=?").run(now, id);
  res.json({ ok: true });
});

// Check partnership between two users
partnersRouter.get('/status', (req, res) => {
  const { a, b } = req.query as { a?: string; b?: string };
  if (!a || !b) return res.status(400).json({ error: 'Missing params' });
  const [userA, userB] = a < b ? [a, b] : [b, a];
  const exists = db.db
    .prepare('SELECT 1 FROM friendships WHERE user_a_id=? AND user_b_id=?')
    .get(userA, userB);
  res.json({ partnered: !!exists });
});

// Fetch partner for a user (if any)
partnersRouter.get('/partner/:uid', requireAuth, (req: AuthedRequest, res) => {
  const { uid } = req.params;
  if (!req.user || req.user.uid !== uid) return res.status(403).json({ error: 'Forbidden' });
  const row = db.db
    .prepare(
      `SELECT CASE WHEN user_a_id = ? THEN user_b_id ELSE user_a_id END as partner_id
       FROM friendships
       WHERE user_a_id = ? OR user_b_id = ?
       LIMIT 1`
    )
    .get(uid, uid, uid) as { partner_id?: string } | undefined;
  if (!row?.partner_id) return res.json({ partnerId: null });
  return res.json({ partnerId: row.partner_id });
});


