import assert from 'node:assert/strict';
import { prisma } from '../apps/api/src/common/prisma';
import { VendorsService, STANDARD_PURCHASE_CATEGORIES } from '../apps/api/src/modules/customers/vendors.service';
import { EmployeeSession, DataScope } from '@anchorpointcrm/shared';

const mockAdminEmployee: EmployeeSession = {
  employeeId: 'usr-admin-test',
  email: 'admin@anchorpointcrm.com',
  firstName: 'Admin',
  lastName: 'Employee',
  roleId: 'role-admin',
  roleName: 'Administrator',
  permissions: ['*'],
  scopes: { '*': DataScope.ORGANIZATION },
  branchId: 'br-main',
  departmentId: 'dept-procurement',
  teamId: null,
  territoryId: null
};

async function runTests() {
  console.log('--- Testing Vendors & Suppliers Module ---');

  // Ensure mock employee exists or find a real admin employee
  let testEmployee = mockAdminEmployee;
  const existingEmployee = await prisma.employee.findFirst({
    where: { isActive: true },
    select: { id: true, email: true, firstName: true, lastName: true, branchId: true }
  });

  if (existingEmployee) {
    testEmployee = {
      ...mockAdminEmployee,
      employeeId: existingEmployee.id,
      email: existingEmployee.email,
      firstName: existingEmployee.firstName,
      lastName: existingEmployee.lastName,
      branchId: existingEmployee.branchId || undefined
    };
  }

  console.log(`Using test employee: ${testEmployee.employeeId} (${testEmployee.email})`);

  // 1. Test getPurchaseCategories
  console.log('Testing getPurchaseCategories...');
  const categories = await VendorsService.getPurchaseCategories();
  assert.ok(Array.isArray(categories), 'Categories should be an array');
  assert.ok(categories.includes('Raw Materials'), 'Should include Raw Materials');
  assert.ok(categories.includes('IT Hardware & Equipment'), 'Should include IT Hardware & Equipment');
  console.log(`✓ Purchase categories verified (${categories.length} categories available)`);

  // 2. Test createVendor
  console.log('Testing createVendor...');
  const createdVendor = await VendorsService.createVendor(testEmployee, {
    name: 'Acme Semiconductor Supplies',
    email: 'sales@acmesemi.example',
    phoneNumber: '9876543210',
    vendorType: 'SUPPLIER',
    category: 'IT Hardware & Equipment',
    purchaseCategories: ['IT Hardware & Equipment', 'Raw Materials'],
    paymentTerms: 'NET_60',
    rating: 5,
    website: 'https://acmesemi.example',
    notes: 'Primary supplier for microcontrollers and power ICs',
    billingAddress: '42 Industrial Park, Sector 5',
    billingCity: 'Bengaluru',
    billingState: 'Karnataka',
    billingCountry: 'IN',
    currency: 'INR'
  } as any);

  assert.ok(createdVendor.id, 'Vendor should have an ID');
  assert.ok(createdVendor.customerNumber.startsWith('VEND-2026'), 'Vendor number should start with VEND-2026');
  assert.equal(createdVendor.name, 'Acme Semiconductor Supplies');
  assert.equal(createdVendor.vendorType, 'SUPPLIER');
  assert.equal(createdVendor.category, 'IT Hardware & Equipment');
  assert.deepEqual(createdVendor.purchaseCategories, ['IT Hardware & Equipment', 'Raw Materials']);
  assert.equal(createdVendor.paymentTerms, 'Net 60');
  console.log(`✓ Vendor created: ${createdVendor.customerNumber} (${createdVendor.id})`);

  // 3. Test listVendors
  console.log('Testing listVendors...');
  const listResult = await VendorsService.listVendors(testEmployee, {
    search: 'Acme Semiconductor',
    vendorType: 'SUPPLIER'
  });

  assert.ok(listResult.total >= 1, 'Should find at least 1 vendor');
  const found = listResult.vendors.find((v) => v.id === createdVendor.id);
  assert.ok(found, 'Created vendor must be present in search results');
  assert.equal(found?.vendorType, 'SUPPLIER');
  console.log(`✓ Vendor listing and search verified (found ${listResult.total} matches)`);

  // 4. Test getVendorById
  console.log('Testing getVendorById...');
  const retrievedVendor = await VendorsService.getVendorById(createdVendor.id, testEmployee);
  assert.equal(retrievedVendor.id, createdVendor.id);
  assert.equal(retrievedVendor.name, 'Acme Semiconductor Supplies');
  assert.equal(retrievedVendor.rating, 5);
  console.log('✓ getVendorById verified');

  // 5. Test updateVendor
  console.log('Testing updateVendor...');
  const updatedVendor = await VendorsService.updateVendor(createdVendor.id, testEmployee, {
    name: 'Acme Semiconductor Global Ltd',
    paymentTerms: 'NET_45',
    rating: 4,
    purchaseCategories: ['IT Hardware & Equipment', 'Raw Materials', 'Packaging & Warehousing']
  });

  assert.equal(updatedVendor.name, 'Acme Semiconductor Global Ltd');
  assert.equal(updatedVendor.paymentTerms, 'Net 45');
  assert.equal(updatedVendor.rating, 4);
  assert.ok(updatedVendor.purchaseCategories.includes('Packaging & Warehousing'));
  console.log('✓ updateVendor verified');

  // 6. Test vendor contacts
  console.log('Testing vendor contacts...');
  const contact = await VendorsService.addContact(createdVendor.id, testEmployee, {
    firstName: 'Jane',
    lastName: 'Doe',
    email: 'jane.doe@acmesemi.example',
    phoneNumber: '9123456789',
    jobTitle: 'Key Account Manager',
    department: 'Sales',
    role: 'Primary Sales Rep'
  });

  assert.ok(contact.id, 'Contact should have an ID');
  assert.equal(contact.firstName, 'Jane');
  assert.equal(contact.role, 'Primary Sales Rep');

  const contactsList = await VendorsService.listContacts(createdVendor.id, testEmployee);
  assert.ok(contactsList.some((c) => c.id === contact.id), 'Contact should appear in vendor contact list');

  const updatedContact = await VendorsService.updateContact(createdVendor.id, contact.id, testEmployee, {
    jobTitle: 'Senior VP Sales',
    role: 'Executive Sponsor'
  });
  assert.equal(updatedContact.jobTitle, 'Senior VP Sales');
  assert.equal(updatedContact.role, 'Executive Sponsor');
  console.log('✓ Vendor contacts (add, list, update) verified');

  // 7. Test vendor notes & activities
  console.log('Testing vendor notes & activities...');
  const note = await VendorsService.createNote(createdVendor.id, testEmployee, {
    title: 'Q3 Vendor Review',
    content: 'Pricing renegotiation scheduled for next quarter. SLA targets met 99.2%.'
  });

  assert.ok(note.id, 'Note should have an ID');
  assert.equal(note.activityType, 'NOTE');
  assert.equal(note.title, 'Q3 Vendor Review');

  const notesList = await VendorsService.listNotes(createdVendor.id, testEmployee);
  assert.ok(notesList.some((n) => n.id === note.id), 'Note should appear in notes list');

  const activity = await VendorsService.createActivity(createdVendor.id, testEmployee, {
    title: 'Procurement Strategy Call',
    activityType: 'MEETING',
    scheduledAt: new Date(Date.now() + 86400000),
    description: 'Discuss silicon wafer delivery timelines and inventory reserves.'
  });

  assert.ok(activity.id, 'Activity should have an ID');
  assert.equal(activity.activityType, 'MEETING');

  const activitiesList = await VendorsService.listActivities(createdVendor.id, testEmployee);
  assert.ok(activitiesList.some((a) => a.id === activity.id), 'Activity should appear in activities list');
  console.log('✓ Vendor notes and activities verified');

  // 8. Test deleteContact and deleteVendor
  console.log('Testing deleteContact and deleteVendor...');
  const delContactResult = await VendorsService.deleteContact(createdVendor.id, contact.id, testEmployee);
  assert.equal(delContactResult.success, true);

  const delVendorResult = await VendorsService.deleteVendor(createdVendor.id, testEmployee);
  assert.equal(delVendorResult.success, true);

  // Confirm soft-deleted
  const trashedCheck = await prisma.customer.findFirst({ where: { id: createdVendor.id, deletedAt: { not: null } } });
  assert.ok(trashedCheck?.deletedAt != null, 'Vendor deletedAt should be set');
  console.log('✓ deleteContact and deleteVendor verified (soft delete intact)');

  // Clean up test records
  await prisma.activity.deleteMany({ where: { customerId: createdVendor.id } });
  await prisma.customerContact.deleteMany({ where: { customerId: createdVendor.id } });
  await prisma.contact.deleteMany({ where: { id: contact.id } });
  await prisma.customer.delete({ where: { id: createdVendor.id } });
  console.log('✓ Cleanup completed');

  console.log('\n🎉 ALL VENDOR MODULE TESTS PASSED!');
}

runTests()
  .catch((err) => {
    console.error('❌ Test failed:', err);
    process.exit(1);
  })
  .finally(async () => {
    await prisma.$disconnect();
  });
