import { query, queryOne, getClient } from '../../config/database.js';
import { NotFoundError, ConflictError, ValidationError } from '../../shared/errors/index.js';

export type PickingType = 'incoming' | 'outgoing' | 'internal';
export type MoveStatus = 'draft' | 'waiting' | 'confirmed' | 'assigned' | 'done' | 'cancelled';

export interface StockMoveLine {
  id?: string;
  product_id: string;
  product_name?: string;
  product_code?: string;
  product_uom_id: string;
  uom_name?: string;
  product_qty: number;
  quantity_done?: number;
  lot_id?: string;
  location_id: string;
  location_name?: string;
  location_dest_id: string;
  location_dest_name?: string;
  status?: MoveStatus;
}

export interface Picking {
  id: string;
  tenant_id: string;
  company_id: string;
  company_name?: string;
  name: string;
  picking_type: PickingType;
  location_id: string;
  location_name?: string;
  location_dest_id: string;
  location_dest_name?: string;
  partner_id?: string;
  partner_name?: string;
  scheduled_date?: Date;
  date_done?: Date;
  origin?: string;
  status: MoveStatus;
  notes?: string;
  moves?: StockMoveLine[];
  created_at: Date;
  validated_at?: Date;
}

export interface CreatePickingDto {
  company_id: string;
  name: string;
  picking_type: PickingType;
  location_id: string;
  location_dest_id: string;
  partner_id?: string;
  scheduled_date?: string;
  origin?: string;
  notes?: string;
  moves: Omit<StockMoveLine, 'id' | 'product_name' | 'product_code' | 'uom_name' | 'location_name' | 'location_dest_name' | 'quantity_done' | 'status'>[];
}

export interface UpdatePickingDto {
  partner_id?: string | null;
  scheduled_date?: string | null;
  origin?: string | null;
  notes?: string | null;
  moves?: Omit<StockMoveLine, 'id' | 'product_name' | 'product_code' | 'uom_name' | 'location_name' | 'location_dest_name' | 'quantity_done' | 'status'>[];
}

export interface PickingFilters {
  company_id?: string;
  picking_type?: PickingType;
  status?: MoveStatus;
  partner_id?: string;
  date_from?: string;
  date_to?: string;
  search?: string;
  page?: number;
  limit?: number;
}

class PickingsService {
  async findAll(tenantId: string, filters: PickingFilters = {}): Promise<{ data: Picking[]; total: number }> {
    const { company_id, picking_type, status, partner_id, date_from, date_to, search, page = 1, limit = 20 } = filters;
    const offset = (page - 1) * limit;

    let whereClause = 'WHERE p.tenant_id = $1';
    const params: any[] = [tenantId];
    let paramIndex = 2;

    if (company_id) {
      whereClause += ` AND p.company_id = $${paramIndex++}`;
      params.push(company_id);
    }

    if (picking_type) {
      whereClause += ` AND p.picking_type = $${paramIndex++}`;
      params.push(picking_type);
    }

    if (status) {
      whereClause += ` AND p.status = $${paramIndex++}`;
      params.push(status);
    }

    if (partner_id) {
      whereClause += ` AND p.partner_id = $${paramIndex++}`;
      params.push(partner_id);
    }

    if (date_from) {
      whereClause += ` AND p.scheduled_date >= $${paramIndex++}`;
      params.push(date_from);
    }

    if (date_to) {
      whereClause += ` AND p.scheduled_date <= $${paramIndex++}`;
      params.push(date_to);
    }

    if (search) {
      whereClause += ` AND (p.name ILIKE $${paramIndex} OR p.origin ILIKE $${paramIndex})`;
      params.push(`%${search}%`);
      paramIndex++;
    }

    const countResult = await queryOne<{ count: string }>(
      `SELECT COUNT(*) as count FROM inventory.pickings p ${whereClause}`,
      params
    );

    params.push(limit, offset);
    const data = await query<Picking>(
      `SELECT p.*,
              c.name as company_name,
              l.name as location_name,
              ld.name as location_dest_name,
              pa.name as partner_name
       FROM inventory.pickings p
       LEFT JOIN auth.companies c ON p.company_id = c.id
       LEFT JOIN inventory.locations l ON p.location_id = l.id
       LEFT JOIN inventory.locations ld ON p.location_dest_id = ld.id
       LEFT JOIN core.partners pa ON p.partner_id = pa.id
       ${whereClause}
       ORDER BY p.scheduled_date DESC NULLS LAST, p.name DESC
       LIMIT $${paramIndex} OFFSET $${paramIndex + 1}`,
      params
    );

    return {
      data,
      total: parseInt(countResult?.count || '0', 10),
    };
  }

  async findById(id: string, tenantId: string): Promise<Picking> {
    const picking = await queryOne<Picking>(
      `SELECT p.*,
              c.name as company_name,
              l.name as location_name,
              ld.name as location_dest_name,
              pa.name as partner_name
       FROM inventory.pickings p
       LEFT JOIN auth.companies c ON p.company_id = c.id
       LEFT JOIN inventory.locations l ON p.location_id = l.id
       LEFT JOIN inventory.locations ld ON p.location_dest_id = ld.id
       LEFT JOIN core.partners pa ON p.partner_id = pa.id
       WHERE p.id = $1 AND p.tenant_id = $2`,
      [id, tenantId]
    );

    if (!picking) {
      throw new NotFoundError('Picking no encontrado');
    }

    // Get moves
    const moves = await query<StockMoveLine>(
      `SELECT sm.*,
              pr.name as product_name,
              pr.code as product_code,
              u.name as uom_name,
              l.name as location_name,
              ld.name as location_dest_name
       FROM inventory.stock_moves sm
       LEFT JOIN inventory.products pr ON sm.product_id = pr.id
       LEFT JOIN core.uom u ON sm.product_uom_id = u.id
       LEFT JOIN inventory.locations l ON sm.location_id = l.id
       LEFT JOIN inventory.locations ld ON sm.location_dest_id = ld.id
       WHERE sm.picking_id = $1
       ORDER BY sm.created_at`,
      [id]
    );

    picking.moves = moves;

    return picking;
  }

  async create(dto: CreatePickingDto, tenantId: string, userId: string): Promise<Picking> {
    if (dto.moves.length === 0) {
      throw new ValidationError('El picking debe tener al menos un movimiento');
    }

    const client = await getClient();

    try {
      await client.query('BEGIN');

      // Create picking
      const pickingResult = await client.query(
        `INSERT INTO inventory.pickings (tenant_id, company_id, name, picking_type, location_id, location_dest_id, partner_id, scheduled_date, origin, notes, created_by)
         VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)
         RETURNING *`,
        [tenantId, dto.company_id, dto.name, dto.picking_type, dto.location_id, dto.location_dest_id, dto.partner_id, dto.scheduled_date, dto.origin, dto.notes, userId]
      );
      const picking = pickingResult.rows[0] as Picking;

      // Create moves
      for (const move of dto.moves) {
        await client.query(
          `INSERT INTO inventory.stock_moves (tenant_id, picking_id, product_id, product_uom_id, location_id, location_dest_id, product_qty, lot_id, created_by)
           VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)`,
          [tenantId, picking.id, move.product_id, move.product_uom_id, move.location_id, move.location_dest_id, move.product_qty, move.lot_id, userId]
        );
      }

      await client.query('COMMIT');

      return this.findById(picking.id, tenantId);
    } catch (error) {
      await client.query('ROLLBACK');
      throw error;
    } finally {
      client.release();
    }
  }

  async confirm(id: string, tenantId: string, userId: string): Promise<Picking> {
    const picking = await this.findById(id, tenantId);

    if (picking.status !== 'draft') {
      throw new ConflictError('Solo se pueden confirmar pickings en estado borrador');
    }

    await query(
      `UPDATE inventory.pickings SET status = 'confirmed', updated_at = CURRENT_TIMESTAMP, updated_by = $1 WHERE id = $2`,
      [userId, id]
    );

    await query(
      `UPDATE inventory.stock_moves SET status = 'confirmed', updated_at = CURRENT_TIMESTAMP, updated_by = $1 WHERE picking_id = $2`,
      [userId, id]
    );

    return this.findById(id, tenantId);
  }

  async validate(id: string, tenantId: string, userId: string): Promise<Picking> {
    const picking = await this.findById(id, tenantId);

    if (picking.status === 'done') {
      throw new ConflictError('El picking ya está validado');
    }

    if (picking.status === 'cancelled') {
      throw new ConflictError('No se puede validar un picking cancelado');
    }

    const client = await getClient();

    try {
      await client.query('BEGIN');

      // Update stock quants for each move
      for (const move of picking.moves || []) {
        const qty = move.product_qty;

        // Decrease from source location
        await client.query(
          `INSERT INTO inventory.stock_quants (product_id, location_id, quantity)
           VALUES ($1, $2, -$3)
           ON CONFLICT (product_id, location_id, COALESCE(lot_id, '00000000-0000-0000-0000-000000000000'))
           DO UPDATE SET quantity = stock_quants.quantity - $3, updated_at = CURRENT_TIMESTAMP`,
          [move.product_id, move.location_id, qty]
        );

        // Increase in destination location
        await client.query(
          `INSERT INTO inventory.stock_quants (product_id, location_id, quantity)
           VALUES ($1, $2, $3)
           ON CONFLICT (product_id, location_id, COALESCE(lot_id, '00000000-0000-0000-0000-000000000000'))
           DO UPDATE SET quantity = stock_quants.quantity + $3, updated_at = CURRENT_TIMESTAMP`,
          [move.product_id, move.location_dest_id, qty]
        );

        // Update move
        await client.query(
          `UPDATE inventory.stock_moves
           SET quantity_done = $1, status = 'done', date = CURRENT_TIMESTAMP, updated_at = CURRENT_TIMESTAMP, updated_by = $2
           WHERE id = $3`,
          [qty, userId, move.id]
        );
      }

      // Update picking
      await client.query(
        `UPDATE inventory.pickings
         SET status = 'done', date_done = CURRENT_TIMESTAMP, validated_at = CURRENT_TIMESTAMP, validated_by = $1, updated_at = CURRENT_TIMESTAMP, updated_by = $1
         WHERE id = $2`,
        [userId, id]
      );

      await client.query('COMMIT');

      return this.findById(id, tenantId);
    } catch (error) {
      await client.query('ROLLBACK');
      throw error;
    } finally {
      client.release();
    }
  }

  async cancel(id: string, tenantId: string, userId: string): Promise<Picking> {
    const picking = await this.findById(id, tenantId);

    if (picking.status === 'done') {
      throw new ConflictError('No se puede cancelar un picking ya validado');
    }

    if (picking.status === 'cancelled') {
      throw new ConflictError('El picking ya está cancelado');
    }

    await query(
      `UPDATE inventory.pickings SET status = 'cancelled', updated_at = CURRENT_TIMESTAMP, updated_by = $1 WHERE id = $2`,
      [userId, id]
    );

    await query(
      `UPDATE inventory.stock_moves SET status = 'cancelled', updated_at = CURRENT_TIMESTAMP, updated_by = $1 WHERE picking_id = $2`,
      [userId, id]
    );

    return this.findById(id, tenantId);
  }

  async delete(id: string, tenantId: string): Promise<void> {
    const picking = await this.findById(id, tenantId);

    if (picking.status !== 'draft') {
      throw new ConflictError('Solo se pueden eliminar pickings en estado borrador');
    }

    await query(`DELETE FROM inventory.pickings WHERE id = $1 AND tenant_id = $2`, [id, tenantId]);
  }
}

export const pickingsService = new PickingsService();
