import 'dotenv/config';
import { PrismaPg } from '@prisma/adapter-pg';
import { PrismaClient } from './generated/prisma/client';
import signJwt, { hashRefreshToken } from './src/common/utils/jwt.util';

const adapter = new PrismaPg({
  connectionString: process.env.DATABASE_URL,
  connectionTimeoutMillis: 5000,
});
const prisma = new PrismaClient({ adapter });

async function upsertUser(email: string, name: string, role: 'USER' | 'AGENT') {
  const user = await prisma.user.upsert({
    where: { email },
    create: {
      email,
      name,
      role,
      isEmailVerified: true,
      isOnboarded: true,
    },
    update: { role, isEmailVerified: true, isOnboarded: true },
  });
  const session = await prisma.session.create({
    data: {
      userId: user.id,
      ipAddress: '127.0.0.1',
      userAgent: 'curl-test',
      expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000),
      status: 'ACTIVE',
    },
  });
  const accessToken = signJwt({ type: 'access', userId: user.id, sessionId: session.id });
  const refreshToken = signJwt({ type: 'refresh', userId: user.id, sessionId: session.id });
  await prisma.session.update({
    where: { id: session.id },
    data: { refreshTokenHash: hashRefreshToken(refreshToken) },
  });
  return { user, cookie: `happydada=${accessToken}; hayyya=${refreshToken}` };
}

async function main() {
  const user = await upsertUser('bookuser@example.com', 'Book User', 'USER');
  const agent = await upsertUser('bookagent@example.com', 'Book Agent', 'AGENT');

  let listing = await prisma.listing.findFirst({ where: { agentId: agent.user.id } });
  if (!listing) {
    listing = await prisma.listing.create({
      data: {
        agentId: agent.user.id,
        title: 'Curl Test House',
        propertyType: 'house',
        listingPurpose: 'rent',
        price: 1200,
        pricePeriod: 'month',
        state: 'Lagos',
        city: 'Ikeja',
        address: '1 Test Street',
        electricity: 'included',
        water: 'included',
        security: 'included',
      },
    });
  }

  console.log('USER_COOKIE=' + user.cookie);
  console.log('AGENT_COOKIE=' + agent.cookie);
  console.log('USER_ID=' + user.user.id);
  console.log('AGENT_ID=' + agent.user.id);
  console.log('LISTING_ID=' + listing.id);
}

main().finally(() => prisma.$disconnect());
